export async function imgCompress(file: any) {
const img = (await fileToImg(file)) as any;
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
const context: CanvasRenderingContext2D | any = canvas.getContext('2d');
const { width: originWidth, height: originHeight } = img;
const scale = +(originWidth / originHeight).toFixed(2);
const targetWidth = 800;
const targetHeight = Math.round(800 / scale);
canvas.width = targetWidth;
canvas.height = targetHeight;
context.clearRect(0, 0, targetWidth, targetHeight);
context.drawImage(img, 0, 0, targetWidth, targetHeight);
const type = 'image/png';
canvas.toBlob(function (blob: any) {
const f = new File([blob], file.name, {
type,
lastModified: file.lastModified,
});
resolve(f);
}, type);
});
}
function fileToImg(file: any) {
return new Promise((resolve, reject) => {
const img = new Image();
const reader = new FileReader();
reader.onload = function (e: HTMLElement | any) {
img.src = e.target.result;
};
reader.onerror = function (e) {
reject(e);
};
reader.readAsDataURL(file);
img.onload = function () {
resolve(img);
};
img.onerror = function (e) {
reject(e);
};
});
}