Compressing a JPEG File - Java 2D Graphics

Java examples for 2D Graphics:JPEG

Description

Compressing a JPEG File

Demo Code


import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Locale;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;

public class Main {

  public void compressJpegFile(File infile, File outfile,
      float compressionQuality) {
    try {//from w ww  .j  av  a 2 s  .c  o  m
      // Retrieve jpg image to be compressed
      RenderedImage rendImage = ImageIO.read(infile);

      // Find a jpeg writer
      ImageWriter writer = null;
      Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
      if (iter.hasNext()) {
        writer = (ImageWriter) iter.next();
      }

      // Prepare output file
      ImageOutputStream ios = ImageIO.createImageOutputStream(outfile);
      writer.setOutput(ios);

      // Set the compression quality
      ImageWriteParam iwparam = new MyImageWriteParam();
      iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
      iwparam.setCompressionQuality(compressionQuality);

      // Write the image
      writer.write(null, new IIOImage(rendImage, null, null), iwparam);

      // Cleanup
      ios.flush();
      writer.dispose();
      ios.close();
    } catch (IOException e) {
    }
  }

}

class MyImageWriteParam extends JPEGImageWriteParam {
  public MyImageWriteParam() {
    super(Locale.getDefault());
  }

  public void setCompressionQuality(float quality) {
    if (quality < 0.0F || quality > 1.0F) {
      throw new IllegalArgumentException("Quality out-of-bounds!");
    }
    this.compressionQuality = 256 - (quality * 256);
  }
}

Related Tutorials