Header Ad

Friday, August 10, 2007

Resize or Cropping of an Image for a fixed Width and Height using Java code

To resize an image for a fixed length and width.... provide,length and width to resize the image returns the new width and height ratio for that image .Take the return parameter split by "." .


import java.awt.Image;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.ImageIcon;

public class ImageResize
{
int setWidth;
int setHeight;
com.jiva.application.auth.AppSession appSession;
public void setWidth(int width)
{
setWidth=width;
}
public void setHeight(int height)
{
setHeight=height;
}

public String imageProps(String path) throws FileNotFoundException, IOException
{
File source=new File(path);
Image inImage = new ImageIcon(source.getAbsolutePath()).getImage();
int imageWidth=inImage.getWidth(null);
int imageHeight=inImage.getHeight(null);
inImage.flush();
int returnImageWidth=setWidth;
int returnImageHeight=setHeight;
double ReturnImageRatio = (double)returnImageWidth/ (double)returnImageHeight;
double ImageRatio = (double)imageWidth / (double)imageHeight;
if (ReturnImageRatio < ImageRatio))
{
returnImageHeight = (int)((double)returnImageWidth / ImageRatio);
}
else
{
returnImageWidth = (int)((double)returnImageHeight * ImageRatio);
}
String x=Integer.toString(returnImageWidth)+"."+Integer.toString(returnImageHeight);

return x;
}
}

No comments: