如何获取图像的 dpi(Java)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7142568/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:49:35  来源:igfitidea点击:

How to get the dpi of an image(Java)

javaimagedpi

提问by guhai

In c#, we can use Image.HorizontalResolution and Image.VerticalResolution.

在 c# 中,我们可以使用 Image.Horizo​​ntalResolution 和 Image.VerticalResolution。

But in java, how to get it?

但是在java中,如何获取呢?

I found ImageInfo.java, but it only support a few image types.

我找到了ImageInfo.java,但它只支持几种图像类型。

http://kickjava.com/src/imageinfo/ImageInfo.java.htm

http://kickjava.com/src/imageinfo/ImageInfo.java.htm

回答by br2000

You can use 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();

回答by Tilman Hausherr

With the help of an ImageReader instance, you can get the image meta data in a neutral format, and then parse it for what you need. A DTD is here.

借助 ImageReader 实例,您可以获得中性格式的图像元数据,然后根据需要对其进行解析。DTD 在这里

    ImageInputStream iis = ImageIO.createImageInputStream(new File(path));
    Iterator it = ImageIO.getImageReaders(iis);
    if (!it.hasNext())
    {
        System.err.println("No reader for this format");
        return;
    }
    ImageReader reader = (ImageReader) it.next();
    reader.setInput(iis);

    IIOMetadata meta = reader.getImageMetadata(0);
    IIOMetadataNode root = (IIOMetadataNode) meta.getAsTree("javax_imageio_1.0");
    NodeList nodes = root.getElementsByTagName("HorizontalPixelSize");
    if (nodes.getLength() > 0)
    {
        IIOMetadataNode dpcWidth = (IIOMetadataNode) nodes.item(0);
        NamedNodeMap nnm = dpcWidth.getAttributes();
        Node item = nnm.item(0);
        int xDPI = Math.round(25.4f / Float.parseFloat(item.getNodeValue()));
        System.out.println("xDPI: " + xDPI);
    }
    else
        System.out.println("xDPI: -");
    if (nodes.getLength() > 0)
    {
        nodes = root.getElementsByTagName("VerticalPixelSize");
        IIOMetadataNode dpcHeight = (IIOMetadataNode) nodes.item(0);
        NamedNodeMap nnm = dpcHeight.getAttributes();
        Node item = nnm.item(0);
        int yDPI = Math.round(25.4f / Float.parseFloat(item.getNodeValue()));
        System.out.println("yDPI: " + yDPI);
    }
    else
        System.out.println("yDPI: -");

(Source/Inspiration: David Thielen)

(来源/灵感来源:David Thielen

Note that you will get a dpi only if it is there.

请注意,只有当它存在时,您才会获得 dpi。

If you wonder what's in the Metadata XML, use this code:

如果您想知道元数据 XML 中有什么,请使用以下代码:

    StringWriter xmlStringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(xmlStringWriter);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // http://stackoverflow.com/a/1264872/535646
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    DOMSource domSource = new DOMSource(root);
    transformer.transform(domSource, streamResult);
    System.out.println (xmlStringWriter);

回答by Adam Magaluk

Get your ImageReader instance. Then use the first ImageReader, set the Input and read IIOImage or only getImageMetadata(pageIndex). You get the image format neutral metadata xml and parse it for the desired data.

获取您的 ImageReader 实例。然后使用第一个 ImageReader,设置 Input 并读取 IIOImage 或仅 getImageMetadata(pageIndex)。您获得图像格式中性元数据 xml 并将其解析为所需的数据。

ImageInputStream iis = ImageIO.createImageInputStream(in);
Iterator it = ImageIO.getImageReaders(iis);
if (!it.hasNext()) {
System.outprintln("No reader for this format");
}
ImageReader reader = (ImageReader) it.next();
reader.setInput(iis);
IIOMetadata meta = reader.getImageMetadata(0);
IIOMetadataNode dimNode = meta.getStandardDimensionNode();
NodeList nodes = dimNode.getElementsByTagName("HorizontalPixelSize");
IIOMetadataNode dpcWidth = (IIOMetadataNode)nodes.nextElement();
nodes = dimNode.getElementsByTagName("VerticalPixelSize");
IIOMetadataNode dpcHeight = (IIOMetadataNode)nodes.nextElement();

// ... calc dot per centimeter to dpi : dpi = dpc / 2.54

// ... 每厘米计算点到 dpi : dpi = dpc / 2.54

The whole image neutral metadata format at

整个图像中性元数据格式在

回答by RiTesh SrivasTav

It is working for me.

它对我有用。

 try {

        final ImageInfo imageInfo = Sanselan.getImageInfo(new File("C:/Users/AngryMan/Desktop/abc.png"));
        final int physicalWidthDpi = imageInfo.getPhysicalWidthDpi();
        final int physicalHeightDpi = imageInfo.getPhysicalHeightDpi();
        System.out.println("physicalWidthDpi :"+physicalWidthDpi );
        System.out.println("physicalHeightDpi : "+physicalHeightDpi);

    } catch (Exception e) {
        e.printStackTrace();
    }

Maven Depndency

Maven依赖

 <!-- https://mvnrepository.com/artifact/org.apache.sanselan/sanselan -->
    <dependency>
        <groupId>org.apache.sanselan</groupId>
        <artifactId>sanselan</artifactId>
        <version>0.97-incubator</version>
    </dependency>

回答by RiTesh SrivasTav

Find dpi of .bmp image use :

查找 .bmp 图像的 dpi 使用:

import com.lowagie.text.Image.

    public class BitmapResolution {
        public static void main(String args[]) {
            try {
                Image img = Image.getInstance("C:/Users/AngryMan/Desktop/img003.bmp");
                System.out.println(img.getDpiX());
                System.out.println(img.getDpiY());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

Maven Dependency :

Maven 依赖:

        <!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>     

回答by heikkim

ImageMagick is a powerful tool for all image related work. IM needs to be installed and requires some configuration for the environment but it's worth the trouble.

ImageMagick 是适用于所有图像相关工作的强大工具。IM 需要安装,需要对环境进行一些配置,但值得麻烦。

http://www.imagemagick.org

http://www.imagemagick.org

I recommend you use JMagick wit IM:

我建议您使用 JMagick 机智 IM:

http://www.jmagick.org

http://www.jmagick.org

I won't explain the details on how tosince it is documented in urls given.

我不会解释有关如何操作的详细信息因为它记录在给定的 url 中。

回答by ciroBorrelli

I found this example interesting:

我发现这个例子很有趣:

ByteArrayInputStream bis = new 
   ByteArrayInputStream(uploadedFile.getContents());
Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader = (ImageReader) readers.next();
IIOMetadata meta = reader.getImageMetadata(0);
Element tree = (Element) meta.getAsTree("javax_imageio_jpeg_image_1.0");
Element jfif = (Element)tree.getElementsByTagName("app0JFIF").item(0);
int dpiH = Integer.parseInt( jfif.getAttribute("Xdensity") );
int dpiV = Integer.parseInt( jfif.getAttribute("Ydensity") );

/* now test that (dpiH == dpiV) */
/* imports are:
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import org.primefaces.model.UploadedFile;
import org.w3c.dom.Element;
*/