enfix
enfix

Reputation: 7000

Bitmap out of memory

I'm tring to get image from gallery (by intent).
I got this error:

985120-byte external allocation too large for this process.
Out of memory: Heap Size=4871KB, Allocated=2472KB, Bitmap Size=19677KB
VM won't let us allocate 985120 bytes

That's my code where I get image:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   ....
   mBitmap = Media.getBitmap(this.getContentResolver(), data.getData());
   ...
}

How can i solve it ?

-------- UPDATE ---------

I noticed that if I select a pre-existent image (HTC photo installed) I get this error. If I select image picked from camera all works fine.

So, I change my code according to this http://developer.android.com/training/displaying-bitmaps/load-bitmap.html:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;

InputStream stream = getContentResolver().openInputStream(data.getData());
mBitmap = BitmapFactory.decodeStream(stream,null,options);
stream.close();

But now the bitmap is NULL !!!

Upvotes: 0

Views: 1562

Answers (2)

Noah Seidman
Noah Seidman

Reputation: 4409

I always wrap decoding in a while loop increasing the inSampleSize and catching OutOfMemoryError. This will give you the maximum possible resolution image. Always use LRU caches!

    Bitmap image;
    boolean success = false;int counter = 0;
    while (success == false && counter < 10)
    {
        try
        {
            image = BitmapFactory.decodeFile(photoPath, options);
            success = true;
        }
        catch(OutOfMemoryError e)
        {
            System.gc();
            options.inSampleSize++;
            counter++;
        }
    }

Upvotes: 0

bjorncs
bjorncs

Reputation: 1270

It looks like your application uses a lot of high-res bitmap (the bitmap memory partition is 19677KB). The sie of 'heap' and 'allocated' are quite normal, and should not be of any problem. Make sure that you remove unused bitmap from memory. You can free a bitmap from memory by calling bitmap.recycle(), or setting the reference to it to null. Take a look at LruCache if you want to cache bitmaps for performance reasons.

Upvotes: 1

Related Questions