简体   繁体   English

Java/ImageIO 在不读取整个文件的情况下获取图像尺寸?

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

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;
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感谢 sfussenegger 的建议

Using ImageReader.getHeight(int) and ImageReader.getWidth(int) normally only reads the image header (I'm looking at JDK6 sources).使用ImageReader.getHeight(int)ImageReader.getWidth(int)通常只读取图像标题(我正在查看 JDK6 源代码)。 So ImageReader is most likely the best choice.所以ImageReader很可能是最好的选择。

You'll have to look into ImageReader.getImageMetadata() .您必须查看ImageReader.getImageMetadata() Unfortunately, The Java Image API is not at all easy to use.不幸的是,Java Image API 并不容易使用。

You can find descriptions of the metadata formats in the package documentation of javax.imageio.metadata .您可以在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).有一些更易于使用的第三方库,例如MediaUtil (上次更新是 3 年前,但对我来说效果很好)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM