Thursday, 16 January 2014

Compress Jpeg Images Through JAVA

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;


/**
 * 
 * @author alekhya
 *
 */
public class CompressJpegImages {

 public static String inputFolder =
       "C:\\Users\\akondam\\Desktop\\images";
 public static String outputFolder = 
       "C:\\Users\\akondam\\Desktop\\CompressedFolderimages";
 public static void main(String[] args) {
  CompressJpegImages cji = new CompressJpegImages();
  cji.listFiles(inputFolder);
 }
  public void listFiles(String directoryName){
   File directory = new File(directoryName);
   //get all the files from a directory
   File[] fList = directory.listFiles();
   for (File file : fList){
   if (file.isFile()){
   compressImageFile(file);
   }
   }
 }
    public void compressImageFile(File file){
    try {
     File compressedImageFile 
      = new File(outputFolder+"//"+file.getName());
     InputStream is = new FileInputStream(file);
     OutputStream os = new FileOutputStream(compressedImageFile);
     float quality = 0.5f;
     // create a BufferedImage as the result of decoding the
     supplied InputStream
     BufferedImage image = ImageIO.read(is);
    // get all image writers for JPG format
    Iterator<ImageWriter> writers =
     ImageIO.getImageWritersByFormatName("jpg");
    if (!writers.hasNext())
 throw new IllegalStateException("No writers found");
 ImageWriter writer = (ImageWriter) writers.next();
 ImageOutputStream ios = ImageIO.createImageOutputStream(os);
 writer.setOutput(ios);
 ImageWriteParam param = writer.getDefaultWriteParam();
        // compress to a given quality
 param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
 param.setCompressionQuality(quality);
 // appends a complete image stream containing a 
        //single image and associated stream and image metadata 
       //and thumbnails to the output 
       writer.write(null, new IIOImage(image, null, null), param);
       // close all streams
       is.close();
       os.close();
       ios.close();
       writer.dispose();
     } catch (FileNotFoundException e) {
 e.printStackTrace();
     } catch (IOException e) {
 e.printStackTrace();
     }
 }

No comments: