我正在使用精美的十二只猴子库来创建TIFF文件,但是在将图像分辨率单位设置为英寸时遇到了问题。我花了两天时间研究Google和十二只猴子的源代码,但均未成功。我希望其他人知道如何解决此问题。这是简化的代码:
final BufferedImage bufferedImage = someImage;
final int dpi = 300;
final String filePath = someFilePath;
final ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final ImageOutputStream output = ImageIO.createImageOutputStream(buffer);
writer.setOutput(output);
final double resolution = dpi / 10.0; // --- This is a hack (possibly a MM/CM conversion)
final String standardFormat = IIOMetadataFormatImpl.standardMetadataFormatName;
final IIOMetadata metadata = writer.getDefaultImageMetadata(ImageTypeSpecifier.createFromRenderedImage(bufferedImage),null);
final IIOMetadataNode customMetadata = new IIOMetadataNode(standardFormat);
final IIOMetadataNode dimensionMetadataNode = new IIOMetadataNode("Dimension");
customMetadata.appendChild(dimensionMetadataNode);
final IIOMetadataNode horizontalMetadataNode = new IIOMetadataNode("HorizontalPixelSize");
dimensionMetadataNode.appendChild(horizontalMetadataNode);
horizontalMetadataNode.setAttribute("value",String.valueOf(resolution));
final IIOMetadataNode verticalMetadataNode = new IIOMetadataNode("VerticalPixelSize");
dimensionMetadataNode.appendChild(verticalMetadataNode);
verticalMetadataNode.setAttribute("value",String.valueOf(resolution));
metadata.mergeTree(standardFormat,customMetadata);
final IIOImage iioImage = new IIOImage(bufferedImage,null,metadata);
writer.write(null,iioImage,params);
final File file = new File(filePath);
final FileOutputStream fos = new FileOutputStream(file);
buffer.writeTo( fos );
此代码创建一个TIFF文件,ImageMagick报告为:
Resolution: 300x300
Print size: 8.26667x11.6933
Units: PixelsPerCentimeter
而且com.twelvemonkeys.imageio.plugins.tiff.TIFF基线状态:
int RESOLUTION_UNIT_NONE = 1;
int RESOLUTION_UNIT_DPI = 2; // Default
int RESOLUTION_UNIT_CENTIMETER = 3;
我知道我可以执行Java的ImageMagick来设置所需的分辨率单位,但这有点麻烦,而从我的Java代码中以正确的分辨率单位生成Tiff文件数据会更好。
如果我的问题很愚蠢(或者我很愚蠢),我事先道歉。我欢迎任何帮助。谢谢。