项目代码封装的一个函数,传入file,type = 1返回file格式,默认返回base64,返回的是promise
// 压缩图片 const compressImg = (file, type) => { let src; let files; const fileSize = parseFloat(parseInt(file.size) / 1024 / 1024).toFixed(2); console.log(fileSize); const read = new FileReader(); read.readAsDataURL(file); return new Promise(((resolve, reject) => { read.onload = function (e) { const img = new Image(); img.src = e.target.result; img.onload = function () { // 默认按比例压缩 const w = this.width; const h = this.height; // 生成canvas const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); let base64; // 创建属性节点 canvas.setAttribute('width', w); canvas.setAttribute('height', h); ctx.drawImage(this, 0, 0, w, h); if (fileSize < 1) { // 如果图片小于一兆 那么不执行压缩操作 base64 = canvas.toDataURL(file.type, 1); } else if (fileSize > 1 && fileSize < 2) { // 如果图片大于1M并且小于2M 那么压缩0.5 base64 = canvas.toDataURL(file.type, 0.1); console.log(base64); } else { // 如果图片超过2m 那么压缩0.2 base64 = canvas.toDataURL(file.type, 0.2); } // 回调函数返回file的值(将base64编码转成file) if (type === 1) { files = dataURLtoFile(base64); } else { // files = dataURLtoFile(base64); // 如果后台接收类型为base64的话这一步可以省略 files = base64; } resolve(files); }; }; })); };
原文:https://www.cnblogs.com/wangkunlong/p/14760786.html