我有一个TIFF图像已经读入我的应用程序并存储在BufferedImage
对象中。如何使用Java Advanced Imaging(JAI)API确定图像的水平和垂直DPI?我一直在四处寻找,但却找不到直接的方法来实现这一目标。
答案 0 :(得分:5)
这是一个完整的示例,使用标准的ImageIO API和标准元数据格式提取DPI(实际上,每mm的像素数)。复杂性,我们来了...... :-P
public class DPITest {
public static void main(String[] args) throws IOException {
File input = new File(args[0]);
ImageInputStream stream = ImageIO.createImageInputStream(input);
Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);
if (readers.hasNext()) {
ImageReader reader = readers.next();
reader.setInput(stream);
IIOMetadata metadata = reader.getImageMetadata(0);
IIOMetadataNode standardTree = (IIOMetadataNode) metadata.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
IIOMetadataNode dimension = (IIOMetadataNode) standardTree.getElementsByTagName("Dimension").item(0);
float horizontalPixelSizeMM = getPixelSizeMM(dimension, "HorizontalPixelSize");
float verticalPixelSizeMM = getPixelSizeMM(dimension, "VerticalPixelSize");
// TODO: Convert pixelsPerMM to DPI left as an exercise to the reader.. ;-)
System.err.println("horizontalPixelSizeMM: " + horizontalPixelSizeMM);
System.err.println("verticalPixelSizeMM: " + verticalPixelSizeMM);
}
else {
System.err.printf("Could not read %s\n", input);
}
}
private static float getPixelSizeMM(final IIOMetadataNode dimension, final String elementName) {
// NOTE: The standard metadata format has defined dimension to pixels per millimeters, not DPI...
NodeList pixelSizes = dimension.getElementsByTagName(elementName);
IIOMetadataNode pixelSize = pixelSizes.getLength() > 0 ? (IIOMetadataNode) pixelSizes.item(0) : null;
return pixelSize != null ? Float.parseFloat(pixelSize.getAttribute("value")) : -1;
}
}
有些消息来源:
答案 1 :(得分:4)
Apache Commons Sanselan库获取图片信息:http://commons.apache.org/imaging/index.html。
final ImageInfo imageInfo = Sanselan.getImageInfo(file);
final int physicalWidthDpi = imageInfo.getPhysicalWidthDpi();
final int physicalHeightDpi = imageInfo.getPhysicalHeightDpi();