// 压缩图片 js
// eslint-disable-next-line no-unused-vars export function compressImage (file, config) { // eslint-disable-next-line no-unused-vars let src // eslint-disable-next-line no-unused-vars let files // let fileSize = parseFloat(parseInt(file['size']) / 1024 / 1024).toFixed(2) const read = new FileReader() read.readAsDataURL(file) return new Promise(function (resolve, reject) { read.onload = function (e) { let img = new Image() img.src = e.target.result img.onload = function () { // 默认按比例压缩 let w = config.width let h = config.height // 生成canvas let canvas = document.createElement('canvas') let ctx = canvas.getContext('2d') let base64 // 创建属性节点 canvas.setAttribute('width', w) canvas.setAttribute('height', h) ctx.drawImage(this, 0, 0, w, h) base64 = canvas.toDataURL(file['type'], config.quality) // 回调函数返回file的值(将base64编码转成file) // files = dataURLtoFile(base64) // 如果后台接收类型为base64的话这一步可以省略 // 回调函数返回file的值(将base64转为二进制) let fileBinary = dataURLtoBlob(base64) resolve(fileBinary) } } }) }; // 将base64转为二进制 function dataURLtoBlob (dataurl) { let arr = dataurl.split(',') let mime = arr[0].match(/:(.*?);/)[1] let bstr = atob(arr[1]) let n = bstr.length let u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new Blob([u8arr], { type: mime }) } // base64转码(将base64编码转回file文件) 此方法我没用到 // eslint-disable-next-line no-unused-vars function dataURLtoFile (dataurl) { let arr = dataurl.split(',') let mime = arr[0].match(/:(.*?);/)[1] let bstr = atob(arr[1]) let n = bstr.length let u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new File([u8arr], { type: mime }) }
调用
let img = new Image(); //获取转成base64的图片的宽高,用来设置压缩过图片的宽高 img.src = file.content; img.onload = ()=>{ that.ImgWidth = img.width; //获取图片的宽 that.ImgHeight = img.height; //获取图片的高 let biLi = that.ImgHeight/that.ImgWidth; //图片的宽高比 let config = { that.ImgWidth>375?375:that.ImgWidth, //设置压缩后图片的款,大于手机宽度375时设置成375 height: that.ImgWidth>375?(375*biLi):that.ImgHeight, //设置压缩后图片的高,通过宽高比来设置高 quality: 0.8 } compressImage(file.file, config).then(result => { //压缩调用 result 胃压缩后的结果 console.log('result') console.log(result) let newdate = new FormData() 转成FormData格式,如有需要 newdate.append('title', file.file.name); newdate.append('tags', 'brand_action_upload'); newdate.append('multipartFile', result); that.upImg(newdate,file.file.name) }) }