title: Compression of PNG using JAI (Java Advanced Imaging)
body: <p>I am using javax.imageio API and JAI for compressing different types of images. It works fine for JPEG using <code>JPEGImageWriter</code> and GIF using <code>GIFImageWriter</code>. But it is not supporting for PNG compression using <code>PNGImageWriter</code> which throws an exception like compression type is not set or "No valid compression", etc. So I used this below <code>ImageWriter</code> for PNG. It works but image quality is too bad. </p>
  
  <p>Can anyone suggest how to use <code>PNGImageWriter</code> for PNG compression and which JAR contains it?</p>
  
  <pre><code>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&lt;ImageWriter&gt;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);
  </code></pre>