js压缩图片base64长度

时间:2022-12-19 23:46:14
 var myCanvas=$('.img-container > img').cropper('getCroppedCanvas');
(function (base64){
var image = new Image(),newBase64,MAX_HEIGHT = 160;
image.onload = function(){
var canvas = document.getElementById("myCanvas");
if(image.height > MAX_HEIGHT) {
image.width *= MAX_HEIGHT / image.height;
image.height = MAX_HEIGHT;
}
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0, image.width, image.height);
newBase64=canvas.toDataURL('image/jpeg',0.4);
      //上传base64编码
$.ajax({
type: "post",
url: '地址',
data: { },
success: function (msg) {
},
error: function (msg) {
tips.error('上传图片服务出错,请稍候再试。')
}
});
console.log('base64Size',newBase64.length/1024); };
image.src = base64;
})(myCanvas.toDataURL('image/jpeg'));

js压缩图片base64长度,不适于与高质量图片;

通过原base64编码在canvas中绘制新图片,并取出canvas使用toDataUrl方法得到新的base64;

绘制图片时通过改变原图片大小和toDataUrl中参数控制图片质量