Java/ImageIO getting image dimensions without reading the entire file?

JavaImageDimensionsjavax.imageio

Java Problem Overview


Is there a way to get the dimensions 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;

Java Solutions


Solution 1 - Java

try(ImageInputStream in = ImageIO.createImageInputStream(resourceFile)){
	final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
	if (readers.hasNext()) {
		ImageReader reader = readers.next();
		try {
			reader.setInput(in);
			return new Dimension(reader.getWidth(0), reader.getHeight(0));
		} finally {
			reader.dispose();
		}
	}
} 

Thanks to sfussenegger for the suggestion

Solution 2 - Java

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.

Solution 3 - Java

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 third party libraries that are easier to use, such as MediaUtil (last updated 3 years ago, but it worked well for me).

Solution 4 - Java

The solution with ImageInputStream and ImageReader is still not so efficient though because they create tmp files. It becomes much slower when image is larger or concurrency is higher, i recommend to use metadata-extractor instead.

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
QuestionPierreView Question on Stackoverflow
Solution 1 - JavaSam BarnumView Answer on Stackoverflow
Solution 2 - JavasfusseneggerView Answer on Stackoverflow
Solution 3 - JavaMichael BorgwardtView Answer on Stackoverflow
Solution 4 - Javakensou97View Answer on Stackoverflow