zulfiqar
zulfiqar

Reputation: 29

How to create bitmap from sdcard images in android?

I need to create a bitmap from sdcard images so after getting uri of image i am getting byte data by opening inputStream as follows

public byte[] getBytesFromFile(InputStream is)
{
    byte[] data = null;
    ByteArrayOutputStream buffer=null;
    try
    {
        buffer = new ByteArrayOutputStream();

        int nRead;
        data = new byte[16384];
        while ((nRead = is.read(data, 0, data.length)) != -1)
        {
            buffer.write(data, 0, nRead);
        }

        buffer.flush();

        return buffer.toByteArray();
    } catch (IOException e)
    {
        return null;
    }
    finally
    {
        if(data!=null)
            data = null;
        if(is!=null)
            try {
                is.close();
            } catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(buffer!=null)
            {
                try {
                    buffer.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                buffer = null;
            }
            System.gc();
    }

after this i am just creating bitmap of that data by following code

byte[] data = getBytesFromFile(is);
Bitmap bm= BitmapFactory.decodeByteArray(data, 0, data.length);

but it gives me outofmemory error. many peoples guide me to check for memory leakages but, this is the first step in my app., i mean thru intent filter i start my app from gallery menu option "share" which invokes my app with the image uri.. plz guide me guys if i am wrong... and also this exception comes on the devices which have high resolution images(size excceds 1MB), but any how it should create Bitmap...

Upvotes: 0

Views: 3620

Answers (1)

Try to use the BitmapFactory.decodeStream() method instead of first loading the bytearray into memory. Also check out this question for more info on loading bitmaps.

Upvotes: 1

Related Questions