maven
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
工具
前端文件直接压缩:来自https://www.cnblogs.com/jinjian91/p/10107208.html
@PostMapping(value = "/upLoadFile")
@ApiOperation(value = "上传文件")
public Result upLoadFile(@RequestParam("file") MultipartFile file) {
try {
log.info("上传文件大小:" + file.getSize() / 1024 + "kb;文件名称:" + file.getOriginalFilename());
ByteArrayOutputStream byteArrayOutputStreamut = new ByteArrayOutputStream();
Thumbnails.of(file.getInputStream())
.scale(0.08f)//放大还是缩小
.outputQuality(0.5f)//图片质量
.toOutputStream(byteArrayOutputStreamut);
log.info("压缩后文件大小:" + byteArrayOutputStreamut.toByteArray().length / 1024 + "kb;");
//下面是上传到阿里云。。。可以忽略
return Result.success(uploadFile.uploadAndReturnUrl(file.getInputStream(), file.getOriginalFilename()));
} catch (IOException e) {
e.printStackTrace();
}
return Result.fail("上传文件失败");
}
import net.coobird.thumbnailator.Thumbnails;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 图片压缩
* @author
*/
@Slf4j
public class ImageCompressUtil {
/**
* 图片质量压缩,不改变大小
* @param file
* @param destPath
* @param quality
* @return
* @throws IOException
*/
public static String compressImage(File file, String destPath, float quality) {
try {
if (!file.exists()) {
log.error("compressImage file not found 文件不存在");
throw new FileNotFoundException("文件不存在");
}
File destFile = new File(destPath);
if (!destFile.exists() && destFile.isDirectory()) {
destFile.mkdirs();
}
String destFileUrl = destPath + File.separator + file.getName();
Thumbnails.of(file)
.scale(1f)
.outputQuality(quality)
.toFile(destFileUrl);
return destFileUrl;
} catch (IOException e) {
log.error("e");
return "";
}
}
/**
* 压缩图片
* @param httpUrl 图片地址
* @param destPath
* @return
*/
public static String compressHttpUrl(String httpUrl, String destPath) {
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
InputStream input = connection.getInputStream();
String destUrl = destPath + httpUrl.substring(httpUrl.lastIndexOf('/'));
Thumbnails.of(input)
.scale(1f)
// .size(200, 500) 大小
// .outputQuality(0.5f) 质量
// .outputFormat("jpg") 图片格式
// .useOriginalFormat() 使用原文件格式
.toFile(destUrl);
input.close();
return destUrl;
} catch (IOException e) {
log.error("压缩图片异常");
return "";
}
}
public static void main(String[] args) {
// String url = "";
// String destPath = "C:/test/image";
// compressImage(new File(url), destPath, 0.25f);
// compressHttpUrl(url, destPath);
}
}