简体   繁体   English

用Java确定图像的DPI

[英]Determine DPI of Image in Java

I have a TIFF image that has been read in to my application and is stored in a BufferedImage object. 我有一个TIFF图像已经读入我的应用程序并存储在BufferedImage对象中。 How can I determine the horizontal and vertical DPI of the image using the Java Advanced Imaging (JAI) APIs? 如何使用Java Advanced Imaging(JAI)API确定图像的水平和垂直DPI? I have been looking around and not been able to find a straight forward way to accomplish this. 我一直在环顾四周,无法找到一种直接的方法来实现这一目标。

Here's a full example extracting DPI (well, pixels per mm, really) using the standard ImageIO API and the standard metadata format. 这是一个完整的示例,使用标准的ImageIO API和标准元数据格式提取DPI(实际上,每mm的像素数)。 Complexity, here we come... :-P 复杂性,我们来了...... :-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;
    }
}

Some sources to read: 一些资料来源:

Apache Commons Sanselan library to get image info: http://commons.apache.org/imaging/index.html . 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();

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

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