不說廢話,直接上代碼
function yaFile(fileList) { return new Promise(function (resolve, reject) { console.log("fileList", fileList); let files = fileList[0].file; console.log("壓縮前大小", files.size); const name = files.name; //文件名 const reader = new FileReader(); reader.readAsDataURL(files); reader.onload = function (e) { const src = e.target.result; const img = new Image(); img.src = src; img.onload = function (e) { const w = img.width; const h = img.height; const maxWidth = 1440; const width = maxWidth; const height = h / w * maxWidth; const quality = 0.8; // 默認圖片質量為0.92 const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const anw = document.createAttribute("width"); anw.nodeValue = width; const anh = document.createAttribute("height"); anh.nodeValue = height; canvas.setAttributeNode(anw); canvas.setAttributeNode(anh); ctx.drawImage(img, 0, 0, width, height); ctx.fillRect(0, 0, width, height); const base64 = canvas.toDataURL('image/jpeg', quality); // 圖片格式jpeg或webp可以選0-1質量區間 // 返回base64轉blob的值 console.log(`原圖${(src.length/1024).toFixed(2)}kb`, `新圖${(base64.length/1024).toFixed(2)}kb`); let file = dataURLtoFile(base64, Date.parse(Date()) + '.jpg'); var newfile = { content: base64, file: file }; console.log("/壓縮后的file", newfile); //壓縮后的file console.log("壓縮后的file大小", newfile.file.size); //壓縮后的file console.log("newfile", newfile); resolve(newfile); } img.onerror = e => { error(e); } } }); }
2.加了Promise同步返回。
3.封裝成工具類 imgUtils.js ,暴露出來
function yaFile(fileList) {
...
}
export default { yaFile }
3.1 main.js引入
import imgUtil from '@/utils/imgUtil' Vue.prototype.$imgUtil=imgUtil
3.2 使用
afterRead() { this.$imgUtil.yaFile(this.fileList).then(res=>{ this.ontpysFile=res; }); }