Edit: this question has actually been already answered at Strange out of memory issue while loading an image to a Bitmap object (the two highest voted answers). It does also use the inSampleSize
option, but with a small method to automatically get the appropriate value.
My original answer:
The inSampleSize
of the BitmapFactory.Options
class can solve your issue (http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize). It works by making a bitmap with the resulting width and height 1/inSampleSize
than the original, thus reducing memory consumption (by inSampleSize
^2?). You should read the doc before using it.
Example:
BitmapFactory.Options options = new BitmapFactory.Options();
// will results in a much smaller image than the original
options.inSampleSize = 8;
// don't ever use a path to /sdcard like this, but I'm sure you have a sane way to do that
// in this case nebulae.jpg is a 19MB 8000x3874px image
final Bitmap b = BitmapFactory.decodeFile("/sdcard/nebulae.jpg", options);
final ImageView iv = (ImageView)findViewById(R.id.image_id);
iv.setImageBitmap(b);
Log.d("ExampleImage", "decoded bitmap dimensions:" + b.getWidth() + "x" + b.getHeight()); // 1000x485
However here it will only work for images up to, I guess, inSampleSize
^2 times the size of the allowed memory and will reduce the quality of small images.
The trick would be to find the appropriate inSampleSize.