使用 Java 在 JPEG 中存储 DPI 和纸张尺寸信息 [英] Storing DPI and Paper Size information in a JPEG with Java

查看:27
本文介绍了使用 Java 在 JPEG 中存储 DPI 和纸张尺寸信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

ImageIO.write(originalImage, OUTPUT_TYPE, resultOutput);

这是对以下 javax.imageio.ImageIO 方法的调用:

This is an invocation of the following javax.imageio.ImageIO method:

public static boolean write(RenderedImage im,
                            String formatName,
                            File output)
                     throws IOException

这会将原始 BMP 图像转换为 JGP 输出.是否可以将 DPI 和纸张尺寸信息也存储在 JPEG 中以帮助打印操作?

This turns an original BMP image into a JGP output. Is it possible to also store DPI and Paper Size information in the JPEG to aid in printing operations?

推荐答案

我发现了这个 在 PNG 文件上设置 DPI 的帖子.它指出您应该使用metadata.mergeTree"来正确保存您的元数据.

I found this post for setting DPI on PNG Files. It pointed out that you should use 'metadata.mergeTree' to properly save your metadata.

考虑到这一点,这里有一些可运行的常规代码,它们采用 BMP 文件并以任意 DPI 创建 JPG 文件:

With that in mind, here is some working groovy code that takes a BMP file and creates a JPG file at arbitrary DPI:

import java.awt.image.BufferedImage
import java.io.File
import java.util.Hashtable
import java.util.Map
import javax.imageio.*
import javax.imageio.stream.*
import javax.imageio.metadata.*
import javax.imageio.plugins.jpeg.*
import org.w3c.dom.*

File sourceFile = new File("sample.bmp")
File destinationFile = new File("sample.jpg")

dpi = 100

BufferedImage sourceImage = ImageIO.read(sourceFile)
ImageWriter imageWriter = ImageIO.getImageWritersBySuffix("jpeg").next();
ImageOutputStream ios = ImageIO.createImageOutputStream(destinationFile);
imageWriter.setOutput(ios);
def jpegParams = imageWriter.getDefaultWriteParam();

IIOMetadata data = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(sourceImage), jpegParams);
Element tree = (Element)data.getAsTree("javax_imageio_jpeg_image_1.0");
Element jfif = (Element)tree.getElementsByTagName("app0JFIF").item(0);
jfif.setAttribute("Xdensity", Integer.toString(dpi));
jfif.setAttribute("Ydensity", Integer.toString(dpi));
jfif.setAttribute("resUnits", "1"); // density is dots per inch                 
data.mergeTree("javax_imageio_jpeg_image_1.0",tree)

// Write and clean up
imageWriter.write(data, new IIOImage(sourceImage, null, data), jpegParams);
ios.close();
imageWriter.dispose();

在 OSX 的预览应用程序中对我来说效果很好,Gimp 都报告结果图像为 100 DPI.至于纸张尺寸……我想这是由 DPI 直接决定的?我找不到任何可以设置该特定值的 JPEG 属性.

Worked fine for me in that OSX's Preview app and Gimp both reported that the resulting image was 100 DPI. As to Paper Size...I imagine this is directly determined by DPI? I couldn't find any JPEG property that would set that particular value.

这篇关于使用 Java 在 JPEG 中存储 DPI 和纸张尺寸信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆