ImageIO saves back to original size

前端 未结 1 1600
不知归路
不知归路 2021-01-23 16:59

I\'ve been searching for some solutions from the internet yet I still haven\'t found an answer to my problem.

I\'ve been working or doing a program that would get an ima

相关标签:
1条回答
  • 2021-01-23 17:36

    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.

    0 讨论(0)
提交回复
热议问题