android: get image dimensions without opening it

Android

Android Problem Overview


I want to get width and height (in pixels) of images which are stored on the sdcard, before loading them into RAM. I need to know the size, so I can downsample them accordingly when loading them. Without downsampling them I get an OutOfMemoryException.

Anyone knows how to get dimensions of image files?

Android Solutions


Solution 1 - Android

Pass the option to just decode the bounds to the factory:

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;

Solution 2 - Android

Actually, there is another way to solve this problem. Using the below way, we can avoid the trouble with file and 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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstoeflnView Question on Stackoverflow
Solution 1 - AndroiddevunwiredView Answer on Stackoverflow
Solution 2 - AndroidTinh DuongView Answer on Stackoverflow