Last active: a year ago
/**
* 图片压缩
* @param base64 被压缩图片的 base64
* @param quality 压缩质量,0 ~ 1 之间,默认 0.2
* @returns
*/
const compressImage = async (
base64: string,
quality = 0.2,
): Promise<string> => {
const img = document.createElement('img');
img.src = base64;
const p = new Promise<string>((resolve, reject) => {
img.addEventListener('load', () => {
const canvas = document.createElement('canvas');
canvas.height = img.height;
canvas.width = img.width;
const ctx = canvas.getContext('2d');
if (!ctx) {
// throw new Error('cannot create canvas context');
return reject('cannot create canvas context');
}
ctx.drawImage(img, 0, 0);
const result = canvas.toDataURL('image/jpeg', quality);
resolve(result);
});
});
return p;
};