mparaz
mparaz

Reputation: 2069

Getting a bitmap's dimensions in Android without reading the entire file

I would like to get a bitmap's dimensions in Android without reading the entire file.

I tried using the recommended inJustDecodeBounds and a custom InputStream that logged the read()s. Unfortunately based on this, the Android BitmapFactory appears to read a large amount of bytes.

Similar to: Java/ImageIO getting image dimensions without reading the entire file? for Android, without using ImageIO.

Upvotes: 7

Views: 2247

Answers (2)

Adam Johns
Adam Johns

Reputation: 36373

java.net.URL imageUrl = new java.net.URL("https://yourUrl.com");
HttpURLConnection connection = (HttpURLConnection)imageUrl.openConnection();
connection.connect();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(connection.getInputStream(), null, options);
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;

Upvotes: 0

IAmGroot
IAmGroot

Reputation: 13865

You are right to use inJustDecodeBounds. Set it to true and make sure to include Options in decode. This just reads the image size.

There is no need to read a stream. Just specify the path in the decode.

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(<pathName>, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;

Upvotes: 14

Related Questions