Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - width and height of bitmap without loading it

Tags:

android

bitmap

I need to get the width and height of a bitmap but using this gives an out of memory exception:

    Resources res=getResources();
    Bitmap mBitmap = BitmapFactory.decodeResource(res, R.drawable.pic); 
    BitmapDrawable bDrawable = new BitmapDrawable(res, mBitmap);

    //get the size of the image and  the screen
    int bitmapWidth = bDrawable.getIntrinsicWidth();
    int bitmapHeight = bDrawable.getIntrinsicHeight();

I read the solution at the question Get bitmap width and height without loading to memory but what would be the inputStream here?

like image 252
Gooey Avatar asked Jul 24 '13 10:07

Gooey


1 Answers

You need to specify some BitmapFactory.Options as well:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;

bDrawable will not contain any bitmap byte array. Taken from here: Setting the inJustDecodeBounds property to true while decoding avoids memory allocation, returning null for the bitmap object but setting outWidth, outHeight and outMimeType. This technique allows you to read the dimensions and type of the image data prior to construction (and memory allocation) of the bitmap.

like image 151
gunar Avatar answered Oct 20 '22 19:10

gunar