After searching SO and reading lots of answers I wrote the following code to get the minimum value of inSampleSize
for downsampling a large bitmap:
public Bitmap load(Context context, String image_url) throws Exception {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image_url, bitmapOptions);
final float imageSize = (float) bitmapOptions.outWidth * (float) bitmapOptions.outHeight * 4.0f / 1024.0f / 1024.0f; // MB
bitmapOptions.inSampleSize = (int) Math.pow(2, Math.floor(imageSize / MemoryManagement.free(context)));
bitmapOptions.inJustDecodeBounds = false;
return BitmapProcessing.modifyOrientation(BitmapFactory.decodeFile(image_url, bitmapOptions), image_url);
}
And
public class MemoryManagement {
public static float free(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass() - 10;
if (memoryClass < 1) memoryClass = 1;
return (float) memoryClass;
}
}
The goal is to get the maximum dimension of bitmap sample without any OutOfMemory exception. Could I trust this code?