How to save optimized png images using java ImageIO?

I create many images in java and save them using the ImageIO.write method as follows:

 final BufferedImage img = createSomeImage(); ImageIO.write( img, "png", new File( "/some/file.png" ); 

I was pleased with the results until Google firefox addon 'Page Speed ​​told me that I could save up to 60% in size if I optimized the images. Images of QR codes, their size is about 900B each, and optimized versions of firefox-plugin are about 300B. I would like to save such optimized 300B images directly from java.

So again my question is: how to save optimized png images using java ImageIO?

+4
source share
1 answer

Use PngEncoderB to convert your BufferedImage to a PNG encoded byte array.

You can apply a filter to it, which will help prepare the image for better optimization. This is what OptiPNG does, only OptiPNG calculates which filter will give you the best compression.

You may need to try applying each filter to find out which one is best for you. With 2-bit color, I think the only filter that can help is up, so I guess the one to be used.

Once you get the image in a PNG encoded byte array, you can write it directly to a file.

+4
source

Source: https://habr.com/ru/post/1307570/


All Articles