Wednesday, January 26, 2011

Maintain Image Aspect Ratio Using Java

In Internet i have searched more about maintaining the aspect ratio of the image using java program.After a long struggle found one example and i changed according to met my requirement.Here you go for the complete solution.
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

class imageAspectRatio {
  public static void main(String args[]) {
  File file = new File("path");//Specify the input image source file location.
    
  try {
   FileInputStream fis = new FileInputStream(file);
   InputStream bis = new BufferedInputStream(fis);
   FileOutputStream fos = null;
   
   Image image = (Image)ImageIO.read(bis);
   
   int thumbWidth = 100;//Specify image width in px
   int thumbHeight = 100;//Specify image height in px
   
   int imageWidth = image.getWidth(null);//get image Widht
   int imageHeight = image.getHeight(null);//get image Height 
   
   double thumbRatio = (double)thumbWidth/(double)thumbHeight;
   double imageRatio = (double)imageWidth/(double)imageHeight;
   
//This calculation is used to convert the image size according to the pixels mentioned above
   if(thumbRatio<imageRatio) {
    thumbHeight = (int) (thumbWidth/imageRatio);
   } else {
    thumbWidth = (int) (thumbHeight*imageRatio);
   }
   
   BufferedImage thumbImage = 
       new BufferedImage(thumbWidth,thumbHeight,BufferedImage.TYPE_INT_RGB);
   
   Graphics2D graphics = thumbImage.createGraphics();
   graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
   graphics.drawImage(image,0, 0, thumbWidth, thumbHeight,null);
   
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   
   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
   JPEGEncodeParam param  = encoder.getDefaultJPEGEncodeParam(thumbImage);
   
   int quality = 100;
   quality = Math.max(0,Math.min(quality,100));
   param.setQuality((float)quality/100.0f,false);
   
//output image type.
   String format = "jpg";
   
   encoder.setJPEGEncodeParam(param);
   encoder.encode(thumbImage);
   ImageIO.write(thumbImage,format, new File("path"));//Specify the location for output image .
    } catch(IOException ioExcep) {
   ioExcep.printStackTrace();
  }catch(Exception excep) {
   excep.printStackTrace();
  }
  }
}

Run this program you will get the expected result.
Do post your comments and for more java programming click this Link.