1 function canvasDataURL(file, callback) { 2 //图片压缩 仅支持jpg jpeg bmp图片格式 不支持png 3 var reader = new FileReader() 4 reader.readAsDataURL(file) 5 reader.onload = function (e) { 6 const img = new Image() 7 var isLt1M = file.size / 1024 / 1024; 8 9 if (isLt1M >= 1) { 10 var quality = 0.2// 图像质量 11 } else if (isLt1M >= 0.48 && isLt1M < 1) { 12 var quality = 0.4 // 图像质量 13 } else { 14 var quality = 0.7 // 图像质量 15 } 16 const canvas = document.createElement('canvas') 17 const drawer = canvas.getContext('2d') 18 img.src = this.result 19 img.onload = function () { 20 canvas.width = img.width 21 canvas.height = img.height 22 drawer.drawImage(img, 0, 0, canvas.width, canvas.height) 23 convertBase64UrlToBlob(canvas.toDataURL(file.type, quality), callback); 24 } 25 } 26 } 27 28 function convertBase64UrlToBlob(urlData, callback) { 29 const arr = urlData.split(',') 30 const mime = arr[0].match(/:(.*?);/)[1] 31 const bstr = atob(arr[1]) 32 let n = bstr.length 33 const u8arr = new Uint8Array(n) 34 while (n--) { 35 u8arr[n] = bstr.charCodeAt(n) 36 } 37 callback(new Blob([u8arr], { 38 type: mime 39 })); 40 } 41 //使用方法 42 canvasDataURL(file,function (blob) { 43 var aafile = new File([blob], file.name, { 44 type: file.type 45 }) 46 47 })