private static final int imgWidth=276;
public static void resizeImage(String targetPath,String sourcePath ){
try {
File srcfile = new File(sourcePath);
if (!srcfile.exists()) {
return;
}
Image src = ImageIO.read(srcfile);
int originalWidth = src.getWidth(null);
int originalHeight = src.getHeight(null);
int amendWidth = originalWidth;
int amendHeight = originalHeight;
if(originalWidth>imgWidth || originalHeight>imgWidth)
{
if(originalWidth/imgWidth>=originalHeight/imgWidth){
amendHeight = imgWidth;
amendWidth = originalWidth*amendHeight/originalHeight;
}else if(originalHeight/imgWidth>originalWidth/imgWidth){
amendWidth = imgWidth;
amendHeight = originalHeight*amendWidth/originalWidth;
}
}
BufferedImage tag = new BufferedImage( amendWidth,
amendHeight, BufferedImage.TYPE_INT_RGB);
/*
* Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
*/
tag.getGraphics().drawImage(
src.getScaledInstance(amendWidth, amendHeight,
Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream out = new FileOutputStream(targetPath);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}