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

fdx2calv  于 2023-05-12  发布在  Android
关注(0)|答案(2)|浏览(131)

我需要获取位图的宽度和高度,但使用此方法会出现内存不足的异常:

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是什么?

kyks70gy

kyks70gy1#

您还需要指定一些BitmapFactory.Options

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将不包含任何位图字节数组。取自此处:
在解码时将inJustDecodeBounds属性设置为true可避免内存分配,为位图对象返回null,但设置outWidth、outHeight和outMimeType。此技术允许您在构造(和分配内存)位图之前读取图像数据的尺寸和类型。

6bc51xsx

6bc51xsx2#

用这个

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

相关问题