前端圖片壓縮
阿新 • • 發佈:2020-08-18
// 壓縮圖片 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 = { width: 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) }) }