Java – How to set DPI information in an image


I have an application that I want to export high-resolution (or rather, high pixel density?) images for printing – for example, I want images that print at 250 dots per inch (DPI), instead of the default, which I understand to be 72 DPI.

I'm using a BufferedImage with a Graphics2D object to draw the image, then ImageIO.write() to save the image.

Any idea how I can set the DPI?

Best Solution

Kurt's answer showed the way, still it took me quite some time to get it run, so here is the code that sets DPI when saving a PNG. There is a lot to do to get the proper writers and such...

 private BufferedImage gridImage;

 private void saveGridImage(File output) throws IOException {

    final String formatName = "png";

    for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) {
       ImageWriter writer =;
       ImageWriteParam writeParam = writer.getDefaultWriteParam();
       ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
       IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);
       if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) {


       final ImageOutputStream stream = ImageIO.createImageOutputStream(output);
       try {
          writer.write(metadata, new IIOImage(gridImage, null, metadata), writeParam);
       } finally {

 private void setDPI(IIOMetadata metadata) throws IIOInvalidTreeException {

    // for PMG, it's dots per millimeter
    double dotsPerMilli = 1.0 * DPI / 10 / INCH_2_CM;

    IIOMetadataNode horiz = new IIOMetadataNode("HorizontalPixelSize");
    horiz.setAttribute("value", Double.toString(dotsPerMilli));

    IIOMetadataNode vert = new IIOMetadataNode("VerticalPixelSize");
    vert.setAttribute("value", Double.toString(dotsPerMilli));

    IIOMetadataNode dim = new IIOMetadataNode("Dimension");

    IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0");

    metadata.mergeTree("javax_imageio_1.0", root);