若依 图片上传压缩 mini调用
一、添加配置
在xxx-common的pom.xml添加:
<!-- 压缩图片thumbnailator-->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.20</version>
</dependency>2、添加类
新包例如com.closs.common.utils.compress 里面加上类 ThumbnailUtils.java
package com.closs.common.utils.compress;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
/**
* 图片压缩工具
*/
public class ThumbnailUtils {
/**
* 判断是否为图片
*/
public static boolean isImage(String fileName) {
String ext = FilenameUtils.getExtension(fileName).toLowerCase();
return ext.equals("jpg")
|| ext.equals("jpeg")
|| ext.equals("png")
|| ext.equals("webp")
|| ext.equals("gif");
}
/**
* 上传后处理图片
*/
public static void process(String path) {
try {
File original = new File(path);
if (!original.exists()) {
return;
}
if (!isImage(original.getName())) {
return;
}
String baseName = path.substring(0, path.lastIndexOf("."));
String ext = path.substring(path.lastIndexOf("."));
File medium = new File(baseName + "_medium" + ext);
File small = new File(baseName + "_small" + ext);
/**
* 1 原图压缩(最大2000px)
*/
Thumbnails.of(original)
.size(2000, 2000) // 最大宽高
.keepAspectRatio(true) // 保持比例
.outputQuality(0.9) // 轻度压缩
.toFile(original);
/**
* 2 生成 medium 图
*/
Thumbnails.of(original)
.width(800)
.keepAspectRatio(true)
.outputQuality(0.8)
.toFile(medium);
/**
* 3 生成 small 图
*/
Thumbnails.of(original)
.width(400)
.keepAspectRatio(true)
.outputQuality(0.8)
.toFile(small);
} catch (Exception e) {
e.printStackTrace();
}
}
}二、调用
在com.closs.common.utils.file 里面加上类 FileUploadUtils.java
找到,
file.transferTo(Paths.get(absPath));在后面添加
// 图片压缩
ThumbnailUtils.process(absPath);例如:
三、压缩对比
四、调用
图片后面拼接
xxx.jpg
xxx_medium.jpg
xxx_small.jpg
