方法一
// Base64转file
function dataURLtoFile(dataurl, file) {
const arr = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
// eslint-disable-next-line no-plusplus
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], file.name, { type: mime });
}
// 压缩图片 参数一:file对象,参数二:压缩图片质量,取值 0~1,默认0,5
export function compressImg(imgFile, quality = 0.5) {
return new Promise((resolve, reject) => {
const cvs = document.createElement('canvas');
const ctx = cvs.getContext('2d');
const filereader = new FileReader();
filereader.readAsDataURL(imgFile);
filereader.onload = e => {
const img = new Image();
img.src = e.target.result;
img.onload = function () {
cvs.width = this.width;
cvs.height = this.height;
ctx.drawImage(img, 0, 0, this.width, this.height);
const dataURL = cvs.toDataURL(imgFile.type, quality);
const file = dataURLtoFile(dataURL, imgFile);
return resolve(file);
};
img.onerror = reject;
};
});
}
方法二:
// Base64转file
function dataURLtoFile(dataurl, file) {
const arr = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
// eslint-disable-next-line no-plusplus
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], file.name, { type: mime });
}
// 压缩图片 参数一:file对象,参数二:压缩图片质量,取值 0~1,默认0,5
export function compressImg(imgFile, quality = 0.5) {
return new Promise((resolve, reject) => {
const cvs = document.createElement('canvas');
const ctx = cvs.getContext('2d');
const img = new Image();
img.src = URL.createObjectURL(imgFile);
img.onload = function () {
cvs.width = this.width;
cvs.height = this.height;
ctx.drawImage(img, 0, 0, this.width, this.height);
const dataURL = cvs.toDataURL(imgFile.type, quality);
const file = dataURLtoFile(dataURL, imgFile);
return resolve(file);
};
img.onerror = reject;
});
}