1 var myCanvas=$('.img-container > img').cropper('getCroppedCanvas'); 2 (function (base64){ 3 var image = new Image(),newBase64,MAX_HEIGHT = 160; 4 image.onload = function(){ 5 var canvas = document.getElementById("myCanvas"); 6 if(image.height > MAX_HEIGHT) { 7 image.width *= MAX_HEIGHT / image.height; 8 image.height = MAX_HEIGHT; 9 } 10 var ctx = canvas.getContext("2d"); 11 ctx.clearRect(0, 0, canvas.width, canvas.height); 12 canvas.width = image.width; 13 canvas.height = image.height; 14 ctx.drawImage(image, 0, 0, image.width, image.height); 15 newBase64=canvas.toDataURL('image/jpeg',0.4);
//上传base64编码 16 $.ajax({ 17 type: "post", 18 url: '地址', 19 data: { 20 21 }, 22 success: function (msg) { 23 42 }, 43 error: function (msg) { 44 tips.error('上传图片服务出错,请稍候再试。') 45 } 46 }); 47 console.log('base64Size',newBase64.length/1024);50 }; 51 image.src = base64; 52 })(myCanvas.toDataURL('image/jpeg'));
js压缩图片base64长度,不适于与高质量图片;
通过原base64编码在canvas中绘制新图片,并取出canvas使用toDataUrl方法得到新的base64;
绘制图片时通过改变原图片大小和toDataUrl中参数控制图片质量