Java/ImageIO 在不读取整个文件的情况下获取图像尺寸?
2022-08-31 14:43:16
有没有办法在不读取整个文件的情况下获取图像的尺寸?
URL url=new URL(<BIG_IMAGE_URL>);
BufferedImage img=ImageIO.read(url);
System.out.println(img.getWidth()+" "+img.getHeight());
img=null;
有没有办法在不读取整个文件的情况下获取图像的尺寸?
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();
}
}
}
感谢sfussenegger的建议
使用ImageReader.getHeight(int)和ImageReader.getWidth(int)通常只读取图像标题(我正在查看JDK6源代码)。因此,ImageReader很可能是最佳选择。