component封装一个图片上传组件的示例(2)

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}) }

最终效果

component封装一个图片上传组件的示例


component封装一个图片上传组件的示例

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/1ba61f2f1e711e690e98ba418dc10f58.html