Android - 无需加载位图即可获取其宽度和高度

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


由于您的图像太大而无法加载到内存中。 - KOTIOS
我也想到了那个.. 因此问题是如何在不加载到内存的情况下获取指标。 - Gooey
2个回答

18

你还需要指定一些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。这种技术允许您在构建(和内存分配)位图之前读取图像数据的尺寸和类型。


2
如果 options.inJustDecodeBounds = true,则 decodeResource 将返回 null;因此,您可以省略 Bitmap bDrawable = BitmapFactory.de 的赋值。另外,您的答案是错误的。您必须从选项中获取宽度和高度。 - Blackbelt

6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接