代碼如下:
1 compressImage(file) { 2 // 參數file,是通過input 選擇本地文件獲取的 3 return new Promise((resolve, reject) => { 4 const { type, name } = file.file 5 let img = new Image() 6 // 創建一個reader實例 7 let reader = new FileReader() 8 9 // 讀取拿到的文件 10 reader.readAsDataURL(file.file) 11 reader.onload = function(e) { 12 13 // 文件加載成功后去轉成Img對象,為了拿到圖片的原始寬高 14 img.src = e.target.result 15 img.onload = function() { 16 // 創建畫布canvas 17 let canvas = document.createElement('canvas') 18 let content = canvas.getContext('2d') 19 20 // 設置畫布的寬高 21 canvas.width = img.width // 需要壓縮到的圖片寬度 22 canvas.height = img.width * (img.height / img.width) 23 24 // 將圖片畫在畫布上 25 content.drawImage(img, 0, 0, canvas.width, canvas.height) 26 27 //畫布轉成blob格式的圖片 28 canvas.toBlob(function(blob) { 29 // blob 格式的圖片 轉成file對象,這里主要看接口支不支持blob格式的文件上傳,如果支持就沒有必要轉 30 let file = new File([blob], name, { type: type }) 31 resolve({type: type, compressFile: file}) 32 }, `image/${type.split('/')[1]}`, 0.7) // 0.7 是文件壓縮程度 33 } 34 } 35 }) 36 },
有問題可以評論哦