15

我需要获取位图的宽度和高度,但使用它会导致内存不足异常:

    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();

我在Get bitmap width and height without loading to memory问题中阅读了解决方案,但是这里的 inputStream 是什么?

4

2 回答 2

18

您还需要指定一些BitmapFactory.Options

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不会包含任何位图字节数组。取自这里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.

于 2013-07-24T10:54:15.363 回答
6

用这个

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

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

于 2013-07-24T10:58:13.700 回答