Vue前端压缩图片

一、在组件包下新建compressImage.js

1 // 压缩图片 2 // eslint-disable-next-line no-unused-vars 3 export function compressImage (file, config) { 4 // eslint-disable-next-line no-unused-vars 5 let src 6 // eslint-disable-next-line no-unused-vars 7 let files 8 // let fileSize = parseFloat(parseInt(file['size']) / 1024 / 1024).toFixed(2) 9 const read = new FileReader() 10 read.readAsDataURL(file) 11 return new Promise(function (resolve, reject) { 12 read.onload = function (e) { 13 let img = new Image() 14 img.src = e.target.result 15 img.onload = function () { 16 // 默认按比例压缩 17 let w = config.width 18 let h = config.height 19 // 生成canvas 20 let canvas = document.createElement('canvas') 21 let ctx = canvas.getContext('2d') 22 let base64 23 // 创建属性节点 24 canvas.setAttribute('width', w) 25 canvas.setAttribute('height', h) 26 ctx.drawImage(this, 0, 0, w, h) 27 // 如果图片超过2m 那么压缩0.2 28 base64 = canvas.toDataURL(file['type'], config.quality) 29       30 // 回调函数返回file的值(将base64编码转成file) 31 // files = dataURLtoFile(base64) // 如果后台接收类型为base64的话这一步可以省略 32 33 // 回调函数返回file的值(将base64转为二进制) 34 let fileBinary = dataURLtoBlob(base64) 35 36 resolve(fileBinary) 37 } 38 } 39 }) 40 }; 41
  // 将base64转为二进制 42 function dataURLtoBlob (dataurl) { 43 let arr = dataurl.split(',') 44 let mime = arr[0].match(/:(.*?);/)[1] 45 let bstr = atob(arr[1]) 46 let n = bstr.length 47 let u8arr = new Uint8Array(n) 48 while (n--) { 49 u8arr[n] = bstr.charCodeAt(n) 50 } 51 return new Blob([u8arr], { type: mime }) 52 } 53 54 // base64转码(将base64编码转回file文件) 此方法我没用到 55 // eslint-disable-next-line no-unused-vars 56 function dataURLtoFile (dataurl) { 57 let arr = dataurl.split(',') 58 let mime = arr[0].match(/:(.*?);/)[1] 59 let bstr = atob(arr[1]) 60 let n = bstr.length 61 let u8arr = new Uint8Array(n) 62 while (n--) { 63 u8arr[n] = bstr.charCodeAt(n) 64 } 65 return new File([u8arr], { type: mime }) 66 }

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

转载注明出处:https://www.heiqu.com/zyjpsf.html