Android development challenges and solutions with Android-Query (AQuery).

Saturday, July 30, 2011

Down Sample Images to avoid Out of Memory Issues in Android

Out of Memory

Memory on phones are scarce. One of the most common case of out of memory (OOM) in Android development is loading images, specially when the source of the images are unknown.

Potential OOM operations include:

Loading a user specified image from the web

We don’ know the size/dimension of the image until it’s downloaded

Loading image from the gallery

Phone cameras capture images with very high resolution

Images will need to be rescaled for normal use

Note that Android allocated the Bitmap images with memory from the overall system, which means that even your application itself have plenty of memory available, OOM errors can still occurs because all the apps share the same memory pool for images (that are decoded with the BitmapFactory).

Downsampling

Downsampling reduce the resolution of an image by taking value of adjacent pixels and average them (a running average) to lower number of pixels.

Since the images in question are too large to be display on the phone regardless, the image is will be shrunk anyway when it’s displayed with a lower width ImageView. When this happens, we are simply wasting memory with loading unnecessarily large raw data.

Therefore, it’s more efficient to down sample the image during the initial load process.