我发现了另一种读取图像大小的方法(更通用)。您可以将ImageIO类与ImageReaders一起使用。这是示例代码:
private Dimension getImageDim(final String path) {
Dimension result = null;
String suffix = this.getFileSuffix(path);
Iterator iter = ImageIO.getImageReadersBySuffix(suffix);
if (iter.hasNext()) {
ImageReader reader = iter.next();
try {
ImageInputStream stream = new FileImageInputStream(new File(path));
reader.setInput(stream);
int width = reader.getWidth(reader.getMinIndex());
int height = reader.getHeight(reader.getMinIndex());
result = new Dimension(width, height);
} catch (IOException e) {
log(e.getMessage());
} finally {
reader.dispose();
}
} else {
log("No reader found for given format: " + suffix));
}
return result;
}
请注意,getFileSuffix是返回路径扩展名而不包含“。”的方法。因此例如:png,jpg等。示例实现为:
private String getFileSuffix(final String path) {
String result = null;
if (path != null) {
result = "";
if (path.lastIndexOf('.') != -1) {
result = path.substring(path.lastIndexOf('.'));
if (result.startsWith(".")) {
result = result.substring(1);
}
}
}
return result;
}
该解决方案非常快,因为仅从文件读取图像大小,而不是从整个图像读取。我对其进行了测试,无法与ImageIO.read的性能进行比较。我希望有人会觉得有用。