How to get the dpi of an image(Java)

2020-03-03 07:34发布

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

But in java, how to get it?

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

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

标签: java image dpi
7条回答
▲ chillily
2楼-- · 2020-03-03 07:45

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.

http://www.imagemagick.org

I recommend you use JMagick wit IM:

http://www.jmagick.org

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

查看更多
看我几分像从前
3楼-- · 2020-03-03 07:47

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.

    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)

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

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

    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);
查看更多
Melony?
4楼-- · 2020-03-03 07:52

You can use Apache Commons Sanselan library to get image info: http://commons.apache.org/imaging/index.html.

final ImageInfo imageInfo = Sanselan.getImageInfo(file_);

final int physicalWidthDpi = imageInfo.getPhysicalWidthDpi();
final int physicalHeightDpi = imageInfo.getPhysicalHeightDpi();
查看更多
Bombasti
5楼-- · 2020-03-03 07:58

Find dpi of .bmp image use :

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 :

        <!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>     
查看更多
淡お忘
6楼-- · 2020-03-03 08:00

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;
*/
查看更多
相关推荐>>
7楼-- · 2020-03-03 08:04

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.

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

The whole image neutral metadata format at

查看更多
登录 后发表回答