Java/ImageIO 在不读取整个文件的情况下获取图像尺寸?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1559253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java/ImageIO getting image dimensions without reading the entire file?
提问by Pierre
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;
采纳答案by Sam Barnum
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 的建议
回答by Michael Borgwardt
You'll have to look into ImageReader.getImageMetadata(). Unfortunately, The Java Image API is not at all easy to use.
你必须调查一下ImageReader.getImageMetadata()。不幸的是,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 年前,但对我来说效果很好)。
回答by sfussenegger
Using ImageReader.getHeight(int)and ImageReader.getWidth(int)normally only reads the image header (I'm looking at JDK6 sources). So ImageReaderis most likely the best choice.
使用ImageReader.getHeight(int)和ImageReader.getWidth(int)通常只读取图像标题(我正在查看 JDK6 源代码)。所以ImageReader很可能是最好的选择。

