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

Pierre picture Pierre · Oct 13, 2009 · Viewed 33.3k times · Source

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;

Answer

Sam Barnum picture Sam Barnum · Oct 13, 2009
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