1、compress(img) 傳入要壓縮的圖片元素,返回一個base64
例如: compress(document.getElementById("img"))
// 圖片壓縮 function compress(img) { let canvas = document.createElement("canvas"); let ctx = canvas.getContext('2d'); //瓦片canvas let tCanvas = document.createElement("canvas"); let tctx = tCanvas.getContext("2d"); let initSize = img.src.length; let width = img.width; let height = img.height; //如果圖片大於四百萬像素,計算壓縮比並將大小壓至400萬以下 let ratio; if ((ratio = width * height / 4000000) > 1) { console.log("大於400萬像素") ratio = Math.sqrt(ratio); width /= ratio; height /= ratio; } else { ratio = 1; } canvas.width = width; canvas.height = height; // 鋪底色 ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, canvas.width, canvas.height); //如果圖片像素大於100萬則使用瓦片繪制 let count; if ((count = width * height / 1000000) > 1) { count = (Math.sqrt(count) + 1); //計算要分成多少塊瓦片 // 計算每塊瓦片的寬和高 let nw = (width / count); let nh = (height / count); tCanvas.width = nw; tCanvas.height = nh; for (let i = 0; i < count; i++) { for (let j = 0; j < count; j++) { tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh); ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh); } } } else { ctx.drawImage(img, 0, 0, width, height); } //進行最小壓縮 let ndata = canvas.toDataURL('image/jpeg', 0.1); console.log('壓縮前:' + initSize); console.log('壓縮后:' + ndata.length); console.log('壓縮率:' + ~~(100 * (initSize - ndata.length) / initSize) + "%"); tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0; return ndata; }
上傳頭像圖片像素比較大,可以進行壓縮之后傳給后台(剪切頭像使用的cropper.js,使用cropper.js實現圖片剪切)

調用上面的 compress 方法進行圖片壓縮

