Gooey
Gooey

Reputation: 4778

Android - width and height of bitmap without loading it

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?

Upvotes: 15

Views: 17383

Answers (2)

gunar
gunar

Reputation: 14710

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 imageWidth = options.outWidth;
int imageHeight = options.outHeight;

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.

Upvotes: 18

nickmartens1980
nickmartens1980

Reputation: 1593

Use this

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

see http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

Upvotes: 6

Related Questions