因为整个系统中需要显示用户一个40*40的小头像,还有一个300*330的大头像,所以就想在用户上传头像时,先把用户上传的源图片,保存起来,经相对路径的形式保存在user类的srcphoto属性中,然后写了一个方法cutImage
public static String cutImage(String srcPath, int width, int height)
throws IOException {
File srcFile = new File(srcPath);
System.out.print(srcFile.exists());
BufferedImage image = ImageIO.read(srcFile);
int srcWidth = image.getWidth(null);
int srcHeight = image.getHeight(null);
int newWidth = 0, newHeight = 0;
int x = 0, y = 0;
double scale_w = (double) width / srcWidth;
double scale_h = (double) height / srcHeight;
System.out.println("scale_w=" + scale_w + ",scale_h=" + scale_h);
// 按原比例缩放图片
if (scale_w < scale_h) {
newHeight = height;
newWidth = (int) (srcWidth * scale_h);
x = (newWidth - width) / 2;
} else {
newHeight = (int) (srcHeight * scale_w);
newWidth = width;
y = (newHeight - height) / 2;
}
BufferedImage newImage = new BufferedImage(newWidth, newHeight,
BufferedImage.TYPE_INT_RGB);
newImage.getGraphics().drawImage(
image.getScaledInstance(newWidth, newHeight,
Image.SCALE_SMOOTH), 0, 0, null);
// 保存缩放后的图片
String fileSufix = srcFile.getName().substring(
srcFile.getName().lastIndexOf(".") + 1);
File destFile = new File(srcFile.getParent(), UUID.randomUUID()
.toString()
+ "." + fileSufix);
// ImageIO.write(newImage, fileSufix, destFile);
// 保存裁剪后的图片
ImageIO.write(newImage.getSubimage(x, y, width, height), fileSufix,
destFile);
return UUID.randomUUID().toString()+ "." + fileSufix;
}
但是将user.srcphoto作为参数传递给此方法时,总是报Can't read input file! 不知道什么原因?