1.导入thumbnailator依赖(用于图片压缩)
pom.xml
net.coobird thumbnailator0.4.14
2.java controller类中接口,接收前端base64码并保存成图片
@RequestMapping("/upload/base64/")
public void uploadbase64(HttpServletRequest req, HttpServletResponse response) {
//获取前端传来的base64码 去掉base64码的data:image/png;base64,
String base64String = req.getParameter("photo").replaceAll("data:image/png;base64,", "");
base64Decoder decoder = new base64Decoder();
try {
// base64解码
byte[] bytes = decoder.decodeBuffer(base64String);
for (int i = 0; i < bytes.length; ++i) {
// 调整异常数据
if (bytes[i] < 0) {
bytes[i] += 256;
}
}
// 生成jpg图片
String uploadfilePath = "XXX.jpg";
String uploadfilePath_compress = "XXX_compress.jpg";
// 生成文件jpg
File imageFile = new File(uploadfilePath);
imageFile.createNewFile();
if (!imageFile.exists()) {
imageFile.createNewFile();
}
OutputStream imageStream = new FileOutputStream(uploadfilePath);
imageStream.write(bytes);
imageStream.flush();
imageStream.close();
boolean compressFlag = MyPicUtil.compressQualityAndSize(uploadfilePath,uploadfilePath_compress, 1f, 0.1f);
if (compressFlag == false) {
return;
}
File oldFile = new File(uploadfilePath);
// 原图片删除
oldFile.delete();
} catch (Exception e) {
log.info("上传错误");
log.error(e.toString(), e);
}
}
3.MyPicUtil.java 图片压缩工具类
@Slf4j
public class MyPicUtil {
public static boolean compressQualityAndSize(String fromfilePath, String tofilePath, Float sizeRatio, Float qualityRatio) {
try {
Thumbnails.of(new File(fromfilePath))
.scale(sizeRatio) //图片大小(长宽)压缩 从0按照
.outputQuality(qualityRatio) //图片质量压缩比例 从0-1,越接近1质量越好
.toOutputStream(new FileOutputStream(tofilePath));
return true;
} catch (IOException e) {
log.warn(e.getMessage());
e.printStackTrace();
return false;
}
}
}
4.前端测试页面
Insert title here
上传照片测试
5.Springboot请求默认上限2mb,可以在yml配置中修改
application.yml
server:
#默认8KB
max-http-header-size: 16KB
tomcat:
#默认2MB
max-http-form-post-size: 4MB
小结:我可以顺利运行,但是前端上传图片转base64码感觉还是有些问题,有时候图片200k转成base64码就变1M多了,而且java压缩的代码有概率压缩后比原来还大,可以加个判断



