Android - 位图的宽度和高度,不加载它

Goo*_*oey 15 android bitmap

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

    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();
Run Code Online (Sandbox Code Playgroud)

我在问题上阅读解决方案获取位图宽度和高度而不加载到内存但这里的inputStream是什么?

gun*_*nar 16

你还需要指定一些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;
Run Code Online (Sandbox Code Playgroud)

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.

  • 如果options.inJustDecodeBounds = true,decodeResource将返回null; 所以你可以省略赋值`Bitmap bDrawable = BitmapFactory.de`.你也回答错了.你必须从选项中获得高度和高度 (2认同)

nic*_*980 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;
Run Code Online (Sandbox Code Playgroud)

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