I am using javax.imageio API and JAI for compressing different types of images. It works fine for JPEG using JPEGImageWriter
and GIF using GIFImageWriter
. But it is not supporting for PNG compression using PNGImageWriter
which throws an exception like compression type is not set or "No valid compression", etc. So I used this below ImageWriter
for PNG. It works but image quality is too bad.
Can anyone suggest how to use PNGImageWriter
for PNG compression and which JAR contains it?
File input = new File("test.png");
InputStream is = new FileInputStream(input);
BufferedImage image = ImageIO.read(is);
File compressedImageFile = new File(input.getName());
OutputStream os =new FileOutputStream(compressedImageFile);
Iterator<ImageWriter>writers =
ImageIO.getImageWritersByFormatName("jpg"); // here "png" does not work
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.5f);
writer.write(null, new IIOImage(image, null, null), param);