Mr X
Mr X

Reputation: 171

Bitmap Image out of memory

I know there is a lot of discussion about android bitmap images out of memory but I was wondering if someone could explain it to me..

Currently in my app I have an activity which lists image thumbnail (low quality) and when I click an image it opens a new activity to view the image full screen. In my 2nd activity class I have:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
bm = BitmapFactory.decodeFile(myImagePath, options);

I then put this into an ImageView to display it. This works and displays my image to its full quality. However if i click back and then click to see that image again (and repeat this 6 times) .. on the 6th time opening the image (activity2) I get an out of memory error saying Heap size=6919KB, Allocated=3125KB, Bitmap Size = 25848KB!

How is bitmap size that big? I assumed it may be creating new instances all the time so I then decided to put a method in my 2nd activity for when the back key is pressed..and in this method I set my bitmap=null and also did System.gc() to clear the garbage collector BUT this did not fix the problem. I still get an out of memory error on the 6th time of clicking on the thumbnail to view the image in full resolution

Can anyone explain why? Thanks

Upvotes: 9

Views: 21559

Answers (2)

IAmGroot
IAmGroot

Reputation: 13865

There is some great information from android that explains it all in detail, and how to overcome this problem here.

Each pixel is 4 Bytes. 6M Pixel = 24MBs

One photo can use up all the Memory.

Bitmaps take up a lot of memory, especially for rich images like photographs. For example, the camera on the Galaxy Nexus takes photos up to 2592x1936 pixels (5 megapixels). If the bitmap configuration used is ARGB_8888 (the default from the Android 2.3 onward) then loading this image into memory takes about 19MB of memory (2592*1936*4 bytes), immediately exhausting the per-app limit on some devices.

Again I point you to this great link I found from another SO Question that has tutorials of how to properly over come the problem.

Upvotes: 16

Idistic
Idistic

Reputation: 6321

inSample size should be set so that the image is scaled to the size of the display area (1 = full size) unless there is some reason you think you need all the bits of the image, so 2 would = 1/2 scale 4 1/4 scale etc.

Also try bm.recycle() when you are finished with the bitmap before using =null

Update

Look at the second answer what does recycle do unless you have already tried that and it didn't work. I have done similar things with loading images and never run out of memory, that's not proof that it will work for you, but it's a best practice as far as I can tell.

Upvotes: 2

Related Questions