图片压缩 通过canvas 获取dataurl 转blob或者是file

it2022-05-05  136

/* * 图片压缩 * @ * */ compressImage(file) { let that = this; return new Promise((resolve, reject) => { const reader = new FileReader(), img = new Image(); const maxSize = 5 * 1024 * 1024; // 最大设置为5M reader.readAsDataURL(file); reader.onload = function () { img.src = this.result; }; const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); img.onload = function () { const originWidth = this.width, originHeight = this.height; const maxWidth = 400, maxHeight = 400; let targetWidth = originWidth, targetHeight = originHeight; // 图片尺寸超过400x400的限制 if (originWidth > maxWidth || originHeight > maxHeight) { if (originWidth / originHeight > maxWidth / maxHeight) { targetWidth = maxWidth; targetHeight = Math.round(maxWidth * (originHeight / originWidth)); } else { targetHeight = maxHeight; targetWidth = Math.round(maxHeight * (originWidth / originHeight)); } } canvas.width = targetWidth; canvas.height = targetHeight; // 清除画布 context.clearRect(0, 0, targetWidth, targetHeight); // 图片压缩 context.drawImage(img, 0, 0, targetWidth, targetHeight); const dataurl = canvas.toDataURL('image/png'); resolve(that.dataURLtoFile(dataurl, file.name)); // canvas.toBlob((blob) => { // resolve(blob) // }, file.type || 'image/png') } }) } /* * dataul to Blob * */ dataURLtoBlob(dataurl) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], {type: mime}); } /* * dataul to File * */ dataURLtoFile(dataurl, filename) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], filename, {type: mime}); }

 


最新回复(0)