Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling large Bitmaps

I have a bunch of image URLs. I have to download these images and display them in my application one-by-one. I am saving the images in a Collection using SoftReferences and also on Sdcard to avoid refetches and improve user experience.

The problem is I dont know anything about the size of the bitmaps. And as it turns out, I am getting OutOfMemoryExceptions sporadically, when I am using BitmapFactory.decodeStream(InputStream) method. So, I chose to downsample the images using BitmapFactory Options(sample size=2). This gave a better output: no OOMs, but this affects the quality of smaller images.

How should I handle such cases? Is there a way to selectively downsample only high resolution images?

like image 215
Samuh Avatar asked Feb 08 '10 10:02

Samuh


People also ask

How do you handle a large bitmap?

Setting the inJustDecodeBounds property to true while decoding avoids memory allocation, returning null for the bitmap object but setting outWidth , outHeight and outMimeType . This technique allows you to read the dimensions and type of the image data prior to construction (and memory allocation) of the bitmap.

How do you handle bitmaps in Android as it takes too much memory?

On Android 2.3. 3 (API level 10) and lower, using recycle() is recommended. If you're displaying large amounts of bitmap data in your app, you're likely to run into OutOfMemoryError errors. The recycle() method allows an app to reclaim memory as soon as possible.

How do you clear a bitmap?

You can use eraseColor on bitmap to set its color to Transparent. It will useable again without recreating it.

What is inSampleSize?

inSampleSize. Added in API level 1. public int inSampleSize. If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap.


1 Answers

There is an option in BitmapFactory.Options class (one I overlooked) named inJustDecodeBounds, javadoc of which reads:

If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.

I used it to find out the actual size of the Bitmap and then chose to down sample it using inSampleSize option. This at least avoids any OOM errors while decoding the file.

Reference:
1. Handling larger Bitmaps
2. How do I get Bitmap info before I decode

like image 152
Samuh Avatar answered Oct 09 '22 04:10

Samuh