1.导入thumbnailator依赖(用于图片压缩)
pom.xml
<!--maven-->
<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.14</version>
</dependency>
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 {
/**
* @Date 11:43 2021/11/30
* @Description 方法描述
* @param: fromfilePath 图片源
* @param: tofilePath 图片输出源
* @param: qualityRatio 压缩质量
* @Return boolean 是否成功
* @Exception
*/
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.前端测试页面
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="/js/jquery.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<div>
<h1>上传照片测试</h1>
<input type="file" name="file" onchange="showImg(this)"><!--选择图片-->
<img id="getImg"/><!-- 选择后展示的图片 -->
<input class="" type="button" id="btnBut" name="上传" > <!-- 提交 -->
</div>
<script type="text/javascript">
function showImg(cell){//获取图片路径赋给img标签,从而展示出所选择的图片
document.getElementById('getImg').src= window.URL.createObjectURL(cell.files[0]);
}
function image2Base64(img) {//转base64的方法
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var dataURL = canvas.toDataURL("image/png");//规定图片是什么格式,image/格式
return dataURL;
}
$("#btnBut").click(function(){
var imgurl =$('#getImg')[0].src;//获取的图片路径
var img = new Image();
img.src=imgurl;
var base64 = image2Base64(img);
UploadPic(base64);
})
function UploadPic(base64) {
$.ajax({//把编号带到后台去
type : 'post',
url : 'java接口',
data:{'photo': base64},
success : function(data){//成功的事件
},
error : function(data){//失败的事件
alert(data);
}
});
}
</script>
</body>
</html>
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压缩的代码有概率压缩后比原来还大,可以加个判断