51

我想在将它们加载到 RAM 之前获取存储在 sdcard 上的图像的宽度和高度(以像素为单位)。我需要知道大小,所以我可以在加载它们时相应地对它们进行下采样。如果不对它们进行下采样,我会得到 OutOfMemoryException。

任何人都知道如何获取图像文件的尺寸?

4

2 回答 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;
于 2012-06-20T21:30:53.957 回答
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);
于 2015-10-05T02:43:02.430 回答