views:

199

answers:

1

I am generating lots of images in java and saving them through the ImageIO.write method like this:

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

I was happy with the results until Google's firefox addon 'Page Speed' told me that i can save up to 60% of the size if i optimize the images. The images are QR codes, their size is around 900B each and the firefox-plugin optimized versions are around 300B. I'd like to save such optimized 300B Images directly from java.

So here my question again: How to save optimized png images with java's ImageIO?

+3  A: 

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

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

You might have to try applying each filter to see which one is consistently better for you. With 2 bit color, I think the only filter that might help is "up", so I'm guessing that's the one to use.

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

Marcus Adams