<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
public class thumbnailator {
/**
* 重新生成图片宽、高
* @param srcPath 图片路径
* @param destPath 新生成的图片路径
* @param newWith 新的宽度
* @param newHeight 新的高度
* @param forceSize 是否强制使用指定宽、高,false:会保持原图片宽高比例约束
* @return
* @throws IOException
*/
public boolean resizeImage (String srcPath, String destPath, int newWith, int newHeight, boolean forceSize) throws IOException {
if (forceSize) {
Thumbnails.of(srcPath).forceSize(newWith, newHeight).toFile(destPath);
} else {
Thumbnails.of(srcPath).width(newWith).height(newHeight).toFile(destPath);
}
return true;
}
}
再来编写SSM框架中使用方法
@RequestMapping("/editinfo/{id}")
public String editinfo(@PathVariable("id")Integer id,
@RequestParam("img")MultipartFile file,
@RequestParam("username")String username,
@RequestParam("motto")String motto,
HttpSession session){
String path = "D:\\IDE\\IDEA_Demo\\Study_SSM08\\src\\main\\webapp\\images\\";//表示到项目的根目录下,要是想到目录下的子文件夹,修改"/"即可
String prefilename = file.getOriginalFilename();
if (file.getOriginalFilename().equals("")){
userService.edituserinfo(id, username, motto);
}else {
String newfilename = UUID.randomUUID()+prefilename.substring(prefilename.lastIndexOf('.'));
String resizefilename = UUID.randomUUID()+prefilename.substring(prefilename.lastIndexOf('.'));
File newfile = new File(path+newfilename);
try {
file.transferTo(newfile);
thumbnailator.resizeImage(path+newfilename,
path+resizefilename,
100,100,true);
} catch (IOException e) {
e.printStackTrace();
return "redirect:/user_info.jsp";
}
userService.edituserinfohaveimg(id, username, motto, "images/"+resizefilename);
}
return "redirect:/editstate/"+id;
}
这是原图
这是修改大小后效果