今天给大家介绍一个非常好用的一个java开源的Thumbnailator图片压缩jar,随着智能手机的像素越来越高,用户把手机拍摄的3-10兆的图片上传到服务器上,在从服务器上面读取上传的图片会加载非常的缓慢,所以只能考虑压缩图片的质量从而保证网站打开的速度。
第一步导入jar:
<!-- 图片压缩 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
常用的格式:
Thumbnails.of("原图文件的路径")
.scale(1f) // 值在0到1之间,1f就是原图大小,0.5就是原图的一半大小
.outputQuality(0.5f) // 值也是在0到1,越接近于1质量越好,越接近于0质量越差
.toFile("压缩后文件的路径");
其他的格式:
1.指定大小比例进行缩放--考虑图片的完整度
size(宽度, 高度)
2.按照比例进行缩放
scale(比例)
3.不按照比例,指定大小进行缩放--不考虑图片的完整度
size(宽度, 高度).keepAspectRatio(false)
4.图片旋转
size(宽度, 高度).rotae(90) -- 旋转90度(必须加size不然报错)
5.水印
BOTTOM_RIGHT 右下角
CENTER 中心
size(宽度, 高度).watermark(Positions.CENTER,)
.size(1280, 1024)
.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("d:/uploadImg/head.png")), 0.5f)
.outputQuality(0.8f)
.toFile(dest);
6.裁剪 -- 以图片中心400*400区域
.sourceRegion(Positions.CENTER, 400,400)
.size(200,200).keepAspectRatio(false)
7.转化图像格式
.size(200,200).outputFormat(".png")
工具类:
/**
* 图片上传压缩
*
* @param file 文件
* @param subdirectory 文件夹名称
* @param width 图片宽度
* @param height 图片高度
* @return
*/
public static Map<String, String> saveImgCompress(MultipartFile file, String subdirectory,Integer width,Integer height) {
//上传文件路径
String path = GetServerPathUtil.getPath("uploadImg");
// 获取文件名称
String filename = file.getOriginalFilename();
String fielhouzhui = filename.substring(filename.lastIndexOf("."), filename.length());
//重新修改文件名防止重名
filename = new SimpleDateFormat("yyyyMMddHHmmssSSS")
.format(new Date())
+ (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000) + StringUtils.getUUID() + fielhouzhui;
File filepath = new File(path, filename);
//判断路径是否存在,没有就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
File img = new File(path + File.separator + filename);
Map<String, String> map = new HashMap<>();
try {
Thumbnails.of(file.getInputStream()).size(width,height).toFile(img);
map.put("res", "success");
map.put("url", filename);
return map;
} catch (IOException e) {
LOG.info(filename + "图片上传失败:" + e);
map.put("res", "error");
return map;
}
}
设置上传的图片存放在项目运行目录下面的某一个文件夹:
/**
* 获取文件目录
*
* @param subdirectory 文件夹名称
* @return
*/
public static String getPath(String subdirectory) {
//获取跟目录---与jar包同级目录的upload目录
File upload = null;
try {
// 获取项目中所在的路径
// C:\Users\Administrator\Desktop\SpringBoot\xx\xx-common\target\classes
File path = new File(ResourceUtils.getURL("classpath:").getPath());
// 判断目录是否存在
if (!path.exists()) path = new File("");
// 项目运行目录 + subdirectory
upload = new File(path.getAbsolutePath(), subdirectory);
//如果不存在则创建目录
if (!upload.exists()) upload.mkdirs();
String realPath = upload + "/";
return realPath;// C:\Users\Administrator\Desktop\SpringBoot\XX\XX-common\target\classes\123/
} catch (FileNotFoundException e) {
LOG.info("GetServerPathUtil===>获取服务器路径发生错误!");
System.err.println("GetServerPathUtil===>获取服务器路径发生错误!");
throw new RuntimeException("获取服务器路径发生错误!");
}
}