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 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.
Here’s a piece of code that does exactly that:
With the AQuery lib for Android, downsampling is even simpler.
Down sample from the Internet
Down sample image from File
Checkout the image loading documentation for more detail.
We hope our guide help your Android development.
If you have issues or have other insights regarding Android image loading / optimization, please feel free to leave a comment!