Kaloyan Roussev
Kaloyan Roussev

Reputation: 14711

How to examine the potential filesize/bitmap size before decoding the bitmap from file path in android?

After using the device camera I get a 52MB bitmap and I decode it this way:

    try {
        bitmapLarge = BitmapFactory.decodeFile(pathName, bitmapOptions);
    } catch (OutOfMemoryError ex) {
        ex.printStackTrace();
        try {
            bitmapOptions.inSampleSize = 2;
            bitmapOptions.inJustDecodeBounds = false;
            bitmapLarge = BitmapFactory.decodeFile(pathName, bitmapOptions);
            bitmapOptions.inSampleSize = 1;
        } catch (OutOfMemoryError ex2) {
            ex2.printStackTrace();
            try {
                bitmapOptions.inSampleSize = 4;
                bitmapOptions.inJustDecodeBounds = false;
                bitmapLarge = BitmapFactory.decodeFile(pathName, bitmapOptions);
            } catch (OutOfMemoryError ex3) {
                ex3.printStackTrace();
                bitmapOptions.inSampleSize = 8;
                bitmapOptions.inJustDecodeBounds = false;
                bitmapLarge = BitmapFactory.decodeFile(pathName, bitmapOptions);
                bitmapOptions.inSampleSize = 1;
            }
            bitmapOptions.inSampleSize = 1;
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        Log.e("resizing bitmap", "#### NULL");
        bitmapLarge = null;
        return null;
    }

I get a huge OutOfMemoryError at the first attempt to decodeFile:

12-15 18:24:24.393: E/dalvikvm-heap(12890): Out of memory on a 51916816-byte allocation.

How do I know what the size of the bitmap would be BEFORE trying to do anything with it?

And even if this is possible, how do I decode it downsampled somehow?

Upvotes: 0

Views: 252

Answers (2)

Blackbelt
Blackbelt

Reputation: 157457

with inJustDecodeBounds = true. You will get back a null bitmap, but the bitmapOptions object will be filled with Bitmap's width and height. Then it is just Mathematic.. You need width * height * 4 bytes to keep your bitmap in memory

Upvotes: 2

tyczj
tyczj

Reputation: 73753

Instead of doing bitmapOptions.inJustDecodeBounds = false; change that to true and you will get back the bounds of the image

you should probably read this too http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

Upvotes: 3

Related Questions