Reputation: 1967
I've an image (3648x2736) around 4.19 MB(size in disk) and I wanted to load it in my application but it crashed as it should because of not enough memory. So to avoid these kind of crashes I put a validator before decoding the images(No, I do not want to use inSampleSize
to make it smaller).
long maxMemory = Runtime.getRuntime().maxMemory();
long nativeUsage = Debug.getNativeHeapAllocatedSize();
long heapSize = Runtime.getRuntime().totalMemory();
long heapRemaining = Runtime.getRuntime().freeMemory();
long memoryLeft = maxMemory - (heapSize - heapRemaining) - nativeUsage;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
int bitmapSize = options.outHeight * options.outWidth * 4;
if (bitmapSize < memoryLeft)
return BitmapFactory.decodeFile(filePath);
Now one thing I want to make sure is, am I calculating bitmapSize
properly ? Because the image file size is only 4.19 MB and memoryLeft
was more than 8 MB, yet app crashed. That means it's storing every pixel as 4 bytes(PNGs), right ? then shouldn't it be 3 bytes for jpeg ? or is there something else I need to know ?
Upvotes: 0
Views: 402
Reputation: 5593
Since Bitmap is just a set of uncompressed pixels no matters what format it is - png or jpeg or else. Only factor you should remember is Bitmap.Config
which describe color scheme for bitmap. For example Config.RGB_565
will take 2 bytes per pixel (5 bit red, 6 bit green, 5 bit green channel) and Config.ARGB_8888
will take 4 bytes per pixel (8 bits per each channel).
You can set Bitmap.Config while decoding image using BitmapFactory.Options.inPreferredConfig
but as I understood from BitmapFactory.Options docs this is not guaranteed.
Upvotes: 1