views:

605

answers:

3

Hi all, is there a way to get the dimension of an image without reading the entire file ?

URL url=new URL(<BIG_IMAGE_URL>);
BufferedImage img=ImageIO.read(url);
System.out.println(img.getWidth()+" "+img.getHeight());
img=null;

Thanks

+1  A: 

You'll have to look into ImageReader.getImageMetadata(). Unfortunately, The Java Image API is not at all easy to use.

You can find descriptions of the metadata formats in the package documentation of javax.imageio.metadata.

There are thrid party libraries that are easier to use, such as MediaUtil (last updated 3 years ago, but it worked well for me).

Michael Borgwardt
+4  A: 

Using ImageReader.getHeight(int) and ImageReader.getWidth(int) normally only reads the image header (I'm looking at JDK6 sources). So ImageReader is most likely the best choice.

sfussenegger
+2  A: 
ImageInputStream in = ImageIO.createImageInputStream(resourceFile);
try {
 final Iterator readers = ImageIO.getImageReaders(in);
 if (readers.hasNext()) {
  ImageReader reader = (ImageReader) readers.next();
  try {
   reader.setInput(in);
   return new Dimension(reader.getWidth(0), reader.getHeight(0));
  } finally {
   reader.dispose();
  }
 }
} finally {
 if (in != null) in.close();
}

Thanks to sfussenegger for the suggestion

Sam Barnum