Compressing Image Using Java


Image compressing is an utility we use almost everyday... being it transferring image to to our near and dear ones, to, uploading image in database , or display it in a website. But, I didn't know that image compressing could be such an easy code until I found this one.

package com.src.compressor;

import java.awt.RenderingHints;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import javax.media.jai.JAI;
import javax.media.jai.OpImage;
import javax.media.jai.RenderedOp;

import com.sun.media.jai.codec.SeekableStream;

/**
 * 
 * @author Srijani Ghosh
 * @since Jul 1, 2014
 * 
 */
public class CompressImage {

 /**
  * @param args
  */
 public static void main(String[] args) {
  try {
   new CompressImage().compress();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
 }

 private void compress() throws FileNotFoundException {
  //input file
  File infile = new File(
    "D:\\WORKSPACE\\ImageCompressor\\image_source\\Jellyfish.jpg");
  
  // destination path for compressed file
  File outfile = new File(
    "D:\\WORKSPACE\\ImageCompressor\\image_compressed\\Jellyfish.jpg");

  BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
    infile));
  BufferedOutputStream bos = new BufferedOutputStream(
    new FileOutputStream(outfile));

  SeekableStream s = SeekableStream.wrapInputStream(bis, true);

  RenderedOp image = JAI.create("stream", s);
  ((OpImage) image.getRendering()).setTileCache(null);

  RenderingHints qualityHints = new RenderingHints(
    RenderingHints.KEY_RENDERING,
    RenderingHints.VALUE_RENDER_QUALITY);

  RenderedOp resizedImage = JAI.create("SubsampleAverage", image, 0.9,
    0.9, qualityHints);

  JAI.create("encode", resizedImage, bos, "JPEG", null);
  
  /*Print the size before and after compression*/
  System.out.println("File size before compression : "+ infile.length()+" Bytes");
  System.out.println("File size after compression : "+ outfile.length()+" Bytes");

 }

}


Please remember to use these jars - sun-jai_codec.jar, sun-jai_core.jar (i.e. add them in the classpath of your project) while running this code.
The output for me was :

File size before compression : 775702 Bytes
File size after compression : 48668 Bytes

Happy Learning!
Don't forget to share!

No comments :

Post a Comment