// 压缩图片 /* config= { width: 100, // 压缩后图片的宽 height: 100, // 压缩后图片的高 如果宽高只传一个值,则保持原比例压缩 quality: 1 // 图片品质(清晰度),取值0-1, } */ export function compressImage(file, config) { let files let fileSize = parseFloat(parseInt(file['size']) / 1024 / 1024).toFixed(2) const read = new FileReader() read.readAsDataURL(file) return new Promise(function (resolve) { read.onload = function (e) { let img = new Image() img.src = e.target.result img.onload = function () { console.log(this.width, this.height) // 默认按比例压缩 const { w, h } = changeRatio(this, config) // 生成canvas let canvas = document.createElement('canvas') let ctx = canvas.getContext('2d') let base64 // 创建属性节点 canvas.setAttribute('width', w) canvas.setAttribute('height', h) ctx.drawImage(this, 0, 0, w, h) if (fileSize < 1) { //如果图片小于1M 那么不执行压缩操作 base64 = canvas.toDataURL(file['type'], config.quality || 1) } else if (fileSize > 1 && fileSize < 2) { //如果图片大于1M并且小于2M 那么压缩0.5 base64 = canvas.toDataURL(file['type'], 0.5); } else { //如果图片超过2m 那么压缩0.2 base64 = canvas.toDataURL(file['type'], 0.2); } // 回调函数返回file的值(将base64编码转成file) files = dataURLtoFile(base64, file['name']) resolve(files) } } }) }; // base64转码(将base64编码转回file文件) function dataURLtoFile(dataurl, fileName) { let arr = dataurl.split(',') let mime = arr[0].match(/:(.*?);/)[1] let bstr = atob(arr[1]) let n = bstr.length let u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new File([u8arr], fileName, { type: mime }) } // 设置图片比例 function changeRatio(img, config) { let w = img.width; let h = img.height; // 图片比例 let ratio = img.width / img.height if (config.width && !config.height) { w = config.width; h = w / ratio; } else if (!config.width && config.height) { h = config.height; w = h * ratio; } else if (config.width && config.height) { w = config.width; h = config.height; } return { w: w, h: h } }