1

For Android when loading an image into memory to make sure we don't go over the RAM limit we usually do

BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;

And then decode the bitmap to find its width and we can decide whether to sample based on that.

My question is, if we are loading the bitmap from local storage (SD card), can't we get the file location of the bitmap:

   File file = new File(mPathToFile);

and then check

   if(file.length()>MAX){

   sampleSize = 2;//2 is just an example
   BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = sampleSize;
    bitmap = BitmapFactory.decodeFile(mPathToFile, options);
    }

Is this wrong? Stupid?

3 Answers 3

2

Is this wrong? Stupid?

No, but it might be too inaccurate. The file size in bytes will not usually represent the actual image size in memory because image files like JPG and PNG are compressed representations of the Bitmap. So the file size is not directly linked to the image size (while they are proportional, you can't necessarily say that a 50K JPG file will be 250x250 pixels).

This also means that 50KB on disk does not mean 50KB once inflated into a Bitmap in memory, because it is compressed. The image itself will likely take closer to 300KB (or more) in memory (the requirements are roughly W * H * 4 bytes for an ARGB_8888 Bitmap).

Doing a bounds decode allows you to make this decision based on the actual size the image will be (and thus how much memory it will actually take up in your program).

Sign up to request clarification or add additional context in comments.

Comments

1

I understand that the heap memory used for processing a bitmap is linked to the image resolution rather than the physical size/length of the file.

My understanding is that an image A of resolution 1280 x 800 uses/requires more heap than an Image B of 640 x 400. And depending on quality file size of B might be greater than A. Correct me if I am wrong

2 Comments

I have this same question, my understanding is similar that image resolution determines bitmap heap usage. Give that assumption you would have a 640x400 image that only has two colors, and therefore small file size, would require as much heap as a 640x400 image with millions of colors (i.e. 24bit color space).
Yes. The system would allocate 4 byte(R,G,B and alpha) for one pixel
0

Android docs on similar topic Loading Large Bitmaps Efficiently

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.