2012-06-20 82 views
38

我希望获取存储在SD卡上的图像的宽度和高度(以像素为单位),然后将它们加载到RAM中。我需要知道尺寸,所以我可以在加载它们时对它们进行缩减采样。如果不下采样他们,我会得到一个OutOfMemoryException。android:在不打开它的情况下获取图像尺寸

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

回答

104

传递到范围只是解码工厂的选项:

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; 

HTH

+1

如何获取密度值? – breceivemail

+0

那工作时options.inJustDecodeBounds = false; – Cabezas

+1

返回0的高度和宽度 – AlwaysConfused

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); 
+0

另请参阅http://stackoverflow.com/questions/23867823/get-image-width-and-height-from-uri?lq=1。 – CoolMind

相关问题