其实很简单
1.首先引进pom
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.7</version>
</dependency>
2.接下来就是压缩并上传图片的代码了
public String upload(MultipartFile file,HttpServletRequest request) {
String filename = file.getOriginalFilename();
String checkImg = ImageUtil.checkImg(filename);
if (StringUtil.isEmpty(checkImg)){
throw new ServiceException(ReturnCode.FILE_INVALID_TYPE);
}
File f = new File(uploadPath);
if (!f.exists()){
f.mkdir();
}
String random = UUID.randomUUID().toString()
try {
Thumbnails.of(file.getInputStream()).scale(0.8f).outputFormat("jpg").outputQuality(0.5).toFile(uploadPath + random);
log.info("上传图片成功,图片路径==>{}",uploadPath);
} catch (IOException e) {
log.info("上传图片失败!");
e.printStackTrace();
}
return "/upload/"+random+".jpg";
}
- uploadPath我是配置在.yml文件中的(自己配置图片上传的目标文件夹)
upload:
path: /data/java/upload/
- 获取配置的图片上传路径
@Value("${upload.path}")
private String uploadPath;
- scale 这个参数是图片的缩放比例(根据自己的要求进行设置)
- outputFormat 这个参数是吧上传的图片转换为jpg格式(我是这样图片所占
的内存就会小一些,根据自己的需求进行设置)- outputQuality 这个参数是图片的质量大小进行压缩
- 代码里的 ImageUtil工具类的代码如下(对上传的文件的类型进行限制,自己可以扩展)
public class ImageUtil {
public static String checkImg(String uploadContentType){
String expandedName = "";
if (uploadContentType.endsWith(".jpg") || uploadContentType.endsWith(".JPG")) {
// IE6上传jpg图片的headimageContentType是image/pjpeg,而IE9以及火狐上传的jpg图片是image/jpeg
expandedName = "jpg";
} else if (uploadContentType.endsWith(".png") || uploadContentType.endsWith(".PNG")) {
// IE6上传的png图片的headimageContentType是"image/x-png"
expandedName = "png";
}
return expandedName;
}
}