Friday, January 25, 2013

How much memory do images in android apps really use?

Recently I had some OutOfMemory issues in one my apps.
After analyzing logcat I could see that one image used as background is taking more then 2MB even though the image in png format was less then 200KB.

At the first look it was confusing, but it is actually only logical when you make yourself think about it little bit more.
Image size in compressed format such as (jpg,png) is one thing , and Bitmap decoded from it and used for actually drawing on screen is something completely different.

After quick research I found exact formula to calculate memory required for bitmap.

Memory required by bitmap image depends on image dimensions and bitmap type.

M =  WIDTH * HEIGHT * 4    (for ARGB_8888 Bitmap -  if you need transparency)
M =  WIDTH * HEIGHT * 2    (for RGB_565 Bitmap - no transparency)

where result M is in bytes and WIDTH and HEIGHT are in pixels.

So using few large images as backgrounds in your layouts can quickly lead to OutOfMemory exception on devices with low memory per app limit.

No comments: