js壓縮圖片base64長度

 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長度,不適於與高質量圖片;ajax

經過原base64編碼在canvas中繪製新圖片,並取出canvas使用toDataUrl方法獲得新的base64;canvas

繪製圖片時經過改變原圖片大小和toDataUrl中參數控制圖片質量post

相關文章
相關標籤/搜索