7

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.

Community
  • 1
  • 1
mparaz
  • 2,049
  • 3
  • 28
  • 47

2 Answers2

14

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;
IAmGroot
  • 13,760
  • 18
  • 84
  • 154
  • 2
    I need to use an `InputStream` because I'm reading from the network. I want to minimize the network traffic. `BitmapFactory` also forwards the method with a file to the stream - http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.1.1_r1/android/graphics/BitmapFactory.java#BitmapFactory.decodeFile%28java.lang.String%2Candroid.graphics.BitmapFactory.Options%29 – mparaz Aug 18 '12 at 14:13
  • 1
    @mparaz Then use `BitmapFactory.decodeStream(InputStream is, Rect outPadding, BitmapFactory.Options opts)`. If you already have, then its likely a limitation of applying this method to a stream over a network. Aka, you may need to get the full stream over the network first before you can decode. – IAmGroot Aug 18 '12 at 15:05
0
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;
Adam Johns
  • 35,397
  • 25
  • 123
  • 176