compress(imgFile) { let _this = this return new Promise((resolve, reject) => { let reader = new FileReader() reader.onload = e => { let img = new Image() img.src = e.target.result img.onload = () => { let canvas = document.createElement('canvas') let ctx = canvas.getContext('2d') canvas.width = img.width canvas.height = img.height // 铺底色 ctx.fillStyle = '#fff' ctx.fillRect(0, 0, canvas.width, canvas.height) ctx.drawImage(img, 0, 0, img.width, img.height) // 进行压缩 let ndata = canvas.toDataURL('image/jpeg', 0.3) resolve(_this.dataURLtoFile(ndata, imgFile.name)) } } reader.onerror = e => reject(e) reader.readAsDataURL(imgFile) }) } // base64 转 Blob dataURLtoBlob(dataurl) { let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new Blob([u8arr], {type: mime}) }, // base64 转 File dataURLtoFile(dataurl, filename) { let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new File([u8arr], filename, {type: mime}) }
最终效果