有时候我们上传图片需要对图片进行压缩,为了减少传输过程的流量损耗,可以选择直接在页面用js进行压缩即可,我这里是直接对图片压缩后获取base64的二进制流,然后我们可以当做字符串参数传输到后台,后台再进行base64解码就可以获取文件啦,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<input type="file" id="image_upload" accept="image/*" >
<script>
var fileInput = document.getElementById("image_upload");
//选择文件
fileInput.addEventListener('change',function(){
//如果未传入文件则中断
if(fileInput.files[0] == undefined){
return;
}
var file = fileInput.files[0];
//FileReader可直接将上传文件转化为二进制流
const img = new Image();
var reader = new FileReader();
reader.readAsDataURL(file);//转化二进制流,异步方法
reader.onload = function(){//完成后this.result为二进制流
// console.log(this.result);
//页面显示文件名
var base64Str = this.result;
img.src = base64Str;
//用onload才能获取值
img.onload=function(){
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var originWidth = img.width;
var originHeight = img.height;
// 最大尺寸限制,这个可以做成配置的
var maxWidth = 1000;
var maxHeight =1000;
// 目标尺寸
var targetWidth = originWidth;
var targetHeight = originHeight;
console.log("当前图片尺寸:originWidth="+originWidth+";originHeight="+originHeight);
//对长或者宽大于最大尺寸的,进行等比例压缩
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > 1) {
// 宽图片
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
}else {
// 高图片
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
console.log("目标图片尺寸:targetWidth="+targetWidth+";targetHeight="+targetHeight);
canvas.width = targetWidth;
canvas.height = targetHeight;
context.clearRect(0, 0, targetWidth, targetHeight);
// 图片绘制
context.drawImage(img, 0, 0, targetWidth, targetHeight);
canvas.toBlob(function(blob) {
console.log(blob);
var a = new FileReader();
a.readAsDataURL(blob);
a.onload = function(){
var b64 = this.result;
var startNum = b64.indexOf("base64,");
startNum = startNum*1 + 7;
//去除前部格式信息(如果有需求)
var baseStr = b64.slice(startNum);
//临时存储二进制流,后台传入要的就是base64的二进制流
console.log("baseStr:"+baseStr);
//比如java后台只需要用如下方法就可以获取文件字节流即可
//byte[] src = Base64.decodeBase64(baseStr);
};
//设置为jpeg才能压缩,若是png可能图片会更大
}, 'image/jpeg');
};
};
});
</script>
</body>
</html>