6

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

guhai
  • 187
  • 1
  • 5
  • 15

7 Answers7

10

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();
br2000
  • 969
  • 11
  • 12
6

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);
Tilman Hausherr
  • 17,731
  • 7
  • 58
  • 97
1

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

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

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>     
Eduardo Yáñez Parareda
  • 9,126
  • 4
  • 37
  • 50
0

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

Adam Magaluk
  • 1,716
  • 20
  • 29
  • 1
    The method getStandardDimensionNode() from the type IIOMetadata is not visible – guhai Aug 22 '11 at 05:40
  • 1
    The method nextElement() is undefined for the type NodeList – guhai Aug 22 '11 at 05:40
  • This is code from a rather old forum post - it is no longer valid. – laura Jan 24 '12 at 19:40
  • I made an edit so that it should work now; alternatively, look at http://www.java-forum.org/java-basics-anfaenger-themen/96982-aufloesung-dpi-tiff-png-bildern-auslesen.html#post617178 – Tilman Hausherr Jan 08 '14 at 15:54
  • @TilmanHausherr for some reason (probably reviewers not reading properly) your edit has been rejected. I suggest adding a new answer. – andyb Jan 08 '14 at 16:00
  • It takes a few days, usually. (Or do you see something that I didn't?) – Tilman Hausherr Jan 08 '14 at 16:34
  • I got it in my review queue and it was rejected 3 to 2. I was one of the 2 who approved. It should never take 2 days to show up as the suggested edits queue is usually empty :) – andyb Jan 08 '14 at 17:10
-1

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.

heikkim
  • 2,955
  • 2
  • 24
  • 34
-2

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;
*/