/** * 图片压缩方法,压缩base64格式图片 * @param {Object} base64 * @param {Object} w */ function compressImage(base64, w) { return new Promise((resolve, reject) => { var img = new Image(); var quality = 0.6; //压缩系数0-1之间 img.src = base64; img.setAttribute("crossOrigin", 'Anonymous'); //url为外域时需要 img.onload = function() { // 等比缩放 let width = img.width; let height = img.height; console.log('++++orginal w:' + width + ',h:' + height) if (width > w) { const rate = height / width height = parseInt(w * rate) width = w } var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); canvas.width = width; canvas.height = height; quality = 0.8; console.log('++++compress w:' + width + ',h:' + height) ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(this, 0, 0, canvas.width, canvas.height); const base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句 resolve(base64); } }) } module.exports = { compressImage: compressImage }