imageio image compression example


  

package nl.kameroom.image;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;

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 ImageService {
	
	public void compressAndWriteImage(BufferedImage img, File destFile) throws Exception {
		
		 Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
         ImageWriter writer = (ImageWriter)iter.next();
         // Prepare output file
         ImageOutputStream ios = ImageIO.createImageOutputStream(destFile);
         writer.setOutput(ios);

         // Set the compression quality
         ImageWriteParam iwparam = writer.getDefaultWriteParam();
         iwparam.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT) ;
         iwparam.setCompressionQuality(0.3F); //between 0.0-1.0

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

         // Cleanup
         ios.flush();
         writer.dispose();
         ios.close();
         
	}
	
	public String validateFile(String contentType, String fileName, String orgFileName, long size) {
		System.out.println("contentType " + contentType);
		System.out.println("fileName " + fileName);
		System.out.println("orgFileName " + orgFileName);
		System.out.println("size " + size);
		final String MAX_SIZE_IMAGES = "2000000";
		
	    String message = "";
	      
	      String mimeType = contentType;
	      
	      if ( mimeType != null && mimeType.startsWith( "image/" ) )
	      {
	         if ( ! (mimeType.equalsIgnoreCase( "image/png") 
	        		 	||  mimeType.equalsIgnoreCase( "image/jpeg") 
	        		 		||  mimeType.equalsIgnoreCase( "image/bmp")
	        		 			||  mimeType.equalsIgnoreCase( "image/jpg")) )
	         {
	        	message = "Invalid File Type";
	            return message;
	         }
	         if ( size > Long.valueOf(MAX_SIZE_IMAGES))
	         {
	        	 message = "Invalid File Size";
		         return message;
	         }
	      }
	      else
	      {
	    	  message = "Invalid File Type";
	          return message;
	         
	      }
		return message;
	}
}

Advertisements

One thought on “imageio image compression example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s