ImageIO saves back to original size

浪尽此生 提交于 2019-12-02 05:54:22

To set the image resolution (of the JFIF segment), you can probably use the IIOMetatada for JPEG.

Something along the lines of:

public class MetadataTest {
    public static void main(String[] args) throws IOException {
        BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_3BYTE_BGR);

        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        writer.setOutput(ImageIO.createImageOutputStream(new File("foo.jpg")));
        ImageWriteParam param = writer.getDefaultWriteParam();

        IIOMetadata metadata = writer.getDefaultImageMetadata(ImageTypeSpecifier.createFromRenderedImage(image), param);
        IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(metadata.getNativeMetadataFormatName());
        IIOMetadataNode jfif = (IIOMetadataNode) root.getElementsByTagName("app0JFIF").item(0);

        jfif.setAttribute("resUnits", "1");
        jfif.setAttribute("Xdensity", "300");
        jfif.setAttribute("Ydensity", "300");

        metadata.mergeTree(metadata.getNativeMetadataFormatName(), root);

        writer.write(null, new IIOImage(image, null, metadata), param);
    }
}

Note: this code should not be used verbatim, but adding iteration, error handling, stream closing etc, clutters the example too much.

See JPEG Image Metadata DTD for documentation on the metadata format, and what options you can control.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!