我有一个应用程序,我想导出高分辨率(或更确切地说,高像素密度?)图像用于打印 - 例如,我想要以每英寸250点(DPI)打印的图像,而不是我理解的默认值为72 DPI.
我正在使用带有Graphics2D对象的BufferedImage来绘制图像,然后使用ImageIO.write()来保存图像.
知道如何设置DPI吗?
Kurt的回答显示了这种方式,仍然花了我相当长的时间来运行它,所以这里是保存PNG时设置DPI的代码.要找到合适的作家,还有很多工作要做......
private BufferedImage gridImage; ... private void saveGridImage(File output) throws IOException { output.delete(); final String formatName = "png"; for (Iteratoriw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) { ImageWriter writer = iw.next(); ImageWriteParam writeParam = writer.getDefaultWriteParam(); ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB); IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam); if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) { continue; } setDPI(metadata); final ImageOutputStream stream = ImageIO.createImageOutputStream(output); try { writer.setOutput(stream); writer.write(metadata, new IIOImage(gridImage, null, metadata), writeParam); } finally { stream.close(); } break; } } 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"); dim.appendChild(horiz); dim.appendChild(vert); IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0"); root.appendChild(dim); metadata.mergeTree("javax_imageio_1.0", root); }