1、實現,自己看代碼去
// 圖片壓縮 // 接收三個參數: // file:是讀取的文件,需要input type="file"獲取或者通過js獲取 // rate:壓縮比例;按照原來圖片的百分比 // maxSize: 壓縮后的最大文件 // rate有則使用rate,最大限制攔截,會判斷rate后是否大於maxSize,如果大於,則剪切,不大於,這rate // fileType:返回內容的類型;file即壓縮后的第一個參數,blob是blob文件,base64是base64文件 // 返回:promise,第一個參數:filePress,即壓縮后的fileType文件;第二個參數:base64,即源文件base64 export const imgPress = ({ file, rate = 1, maxSize = 800, fileType = 'file' }) => { return new Promise(resolve => { // new一個文件讀取方法,監聽文件讀取 let reader = new FileReader() reader.readAsDataURL(file) let img = new Image() reader.onload = function (e) { img.src = e.target.result } img.onload = function () { let canvas = document.createElement('canvas') let context = canvas.getContext('2d') // 文件大小KB const fileSizeKB = file.size / 1024 // 配置rate和maxSize的關系 if (fileSizeKB * rate > maxSize) { rate = Math.floor(maxSize / fileSizeKB * 10) / 10 } // 縮放比例,默認0.5 let targetW = canvas.width = this.width * rate let targetH = canvas.height = this.height * rate context.clearRect(0, 0, targetW, targetH) context.drawImage(img, 0, 0, targetW, targetH) if (fileType === 'file' || fileType === 'blob') { canvas.toBlob(function (blob) { resolve({ filePress: fileType === 'blob' ? blob : new File([blob], file.name, { type: file.type }), base64: img.src }) }) } else { resolve({ filePress: fileType === 'base64' ? canvas.toDataURL(file.type) : null, base64: img.src }) } } }) }
壓縮算法涉及canvas,計算量大了,很容易導致瀏覽器假死,可以參考之前的webwork去實現,實際上webwork並不是那么好用。。。所以,該代碼沒有使用結合webwork