public void generateThumbnail(String imgPath, int imgWidth, int imgHeight)
{
try
{
//Assumptions
//imgPath contains the imagefilename, BUT NOT THE EXTENSION
System.out.println("Image width : "+imgWidth+" Image Height : "+imgHeight);
String fs = System.getProperty("file.separator");
double ratio1=((double)Constants.Thumbnail_x) /Constants.Thumbnail_y;
double ratio2= ((double)imgWidth)/imgHeight ;
double ratio3 = 0;
int newImgWidth=0, newImgHeight=0;
int startX = 0, startY = 0;
if(ratio1 > ratio2)
{
ratio3 = ((double)Constants.Thumbnail_y) / imgHeight;
newImgWidth = (int)(imgWidth * ratio3);
startX = (Constants.Thumbnail_x - newImgWidth)/2;
}
else
{
ratio3 = ((double)Constants.Thumbnail_x) / imgWidth;
newImgHeight = (int)(imgHeight * ratio3);
startY = (Constants.Thumbnail_y - newImgHeight)/2;
}
System.out.println("ratio3 : "+ratio3);
BufferedImage imageBuffer = new BufferedImage(Constants.Thumbnail_x, Constants.Thumbnail_y, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = imageBuffer.createGraphics();
double scaleX = ratio3, scaleY = ratio3;
//System.out.println("image file path : "+imgPath);
File file = new File(imgPath+".png");
BufferedImage bi = ImageIO.read(file);
AffineTransform at = new AffineTransform();
at.scale(scaleX, scaleY);
AffineTransformOp ato = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
g.drawImage(bi, ato, startX, startY);
String writePath=imgPath+"-tmb.png";
System.out.println("Image filepath : "+writePath);
ImageIO.write(imageBuffer, "png", new File(writePath));
char fs1 = fs.charAt(0);
String writeFile = writePath.substring(writePath.lastIndexOf(fs1)+1,writePath.length());
//writecode to write the file to disk
}
catch(Exception e)
{
System.out.println("Exception in DrawingUtils generateThumbnail() : ");e.printStackTrace();
}
}
No comments:
Post a Comment