接口接收base64转MultipartFile并压缩图片
依赖
<!-- 压缩图片依赖 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<!-- file 转 MultipartFile 依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
base64转MultipartFile工具类
package com.fillke.file.util;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import java.io.*;
/**
* Description: base64 转 MultipartFile
*
* @author qts
* @date Created on 2022/8/5
*/
public class BASE64DecodedMultipartFile implements MultipartFile {
private final byte[] imgContent;
private final String header;
public BASE64DecodedMultipartFile(byte[] imgContent, String header) {
this.imgContent = imgContent;
this.header = header.split(";")[0];
}
@Override
public String getName() {
return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
}
@Override
public String getOriginalFilename() {
return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
}
@Override
public String getContentType() {
return header.split(":")[1];
}
@Override
public boolean isEmpty() {
return imgContent == null || imgContent.length == 0;
}
@Override
public long getSize() {
return imgContent.length;
}
@Override
public byte[] getBytes() throws IOException {
return imgContent;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(imgContent);
}
@Override
public void transferTo(File file) throws IOException, IllegalStateException {
new FileOutputStream(file).write(imgContent);
}
public static MultipartFile base64ToMultipart(String base64) {
try {
String[] baseStrs = base64.split(",");
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = new byte[0];
b = decoder.decodeBuffer(baseStrs[1]);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new BASE64DecodedMultipartFile(b, baseStrs[0]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
代码
String base64 = "";
// 临时文件
File tempFile = null;
if (StrUtil.isNotBlank(base64 )) {
// 将base64转成 MultipartFile
MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(deployProgram.getPic());
// 压缩图片
String originalFilename = multipartFile.getOriginalFilename();
String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
tempFile = File.createTempFile(UUID.randomUUID().toString(), prefix);
// 需引入对应依赖
Thumbnails.of(multipartFile.getInputStream())
.scale(0.6) //图片大小(长宽)压缩比例 从0-1,1表示原图
.outputQuality(0.6) //图片质量压缩比例 从0-1,越接近1质量越好
.toFile(tempFile);
MultipartFile reduceMultipartFile = new MockMultipartFile("file", tempFile.getName(), null, new FileInputStream(tempFile));
}
// 删除临时file
if (tempFile != null) {
tempFile.deleteOnExit();
}