feat: img compress;perf: color.prompt response

This commit is contained in:
archer
2023-05-03 21:42:23 +08:00
parent 17a42ac0cc
commit 91b02bbfd9
7 changed files with 87 additions and 19 deletions

View File

@@ -190,3 +190,67 @@ export const fileToBase64 = (file: File) => {
reader.onerror = (error) => reject(error);
});
};
/**
* compress image. response base64
* @param maxSize The max size of the compressed image
*/
export const compressImg = ({
file,
maxW = 200,
maxH = 200,
maxSize = 1024 * 100
}: {
file: File;
maxW?: number;
maxH?: number;
maxSize?: number;
}) =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const img = new Image();
// @ts-ignore
img.src = reader.result;
img.onload = () => {
let width = img.width;
let height = img.height;
if (width > height) {
if (width > maxW) {
height *= maxW / width;
width = maxW;
}
} else {
if (height > maxH) {
width *= maxH / height;
height = maxH;
}
}
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
if (!ctx) {
return reject('压缩图片异常');
}
ctx.drawImage(img, 0, 0, width, height);
const compressedDataUrl = canvas.toDataURL(file.type, 1);
// 移除 canvas 元素
canvas.remove();
if (compressedDataUrl.length > maxSize) {
return reject('图片太大了');
}
resolve(compressedDataUrl);
};
};
reader.onerror = (err) => {
console.log(err);
reject('压缩图片异常');
};
});