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

给你一囗甜甜゛ 提交于 2019-11-26 02:51:33

问题


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;

回答1:


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




回答2:


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.




回答3:


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).



来源:https://stackoverflow.com/questions/1559253/java-imageio-getting-image-dimensions-without-reading-the-entire-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!