Android:在不打开图像的情况下获取其尺寸

51

在将存储在SD卡上的图像加载到内存之前,我想获取图像的宽度和高度(以像素为单位)。我需要知道图像的大小,以便在加载时适当地降采样它们。如果不降采样,我会出现OutOfMemoryException。

有人知道如何获取图像文件的尺寸吗?

2个回答

127

将选项传递给工厂,仅解码边界:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;

//Returns null, sizes are in the options variable
BitmapFactory.decodeFile("/sdcard/image.png", options);
int width = options.outWidth;
int height = options.outHeight;
//If you want, the MIME type will also be decoded (if possible)
String type = options.outMimeType;

1
如何获取密度值? - Bobs
3
高度和宽度返回0。 - AlwaysConfused
如果uri类似于“images/1234/get”,其中不包括图像格式,是否有可能获取尺寸?@Devunwired - inverted_index
1
这个仍然处理图像,当检查多个图像时,花费的时间太长,即使decodeFile不为其分配内存,它仍然会处理整个图像。 - M D P

2
实际上,还有另一种解决这个问题的方法。使用下面的方式,我们可以避免文件和URI的麻烦。
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
ParcelFileDescriptor fd = mContext.getContentResolver().openFileDescriptor(u, "r"); // u is your Uri
BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, options);

请参见https://dev59.com/_YDaa4cB1Zd3GeqP-wjY?lq=1。 - CoolMind

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