1.可以设置压缩后的图片最大宽度/高度。 限制输出最大宽/高值 (如果不设置,按照原图尺寸大小)
2.要求输出格式支持blob 和 File 文件。
3.可以设置输出图片的质量级别(假设1-10级别。级别越大,质量越高,占用存储越大,越清晰)
- 首先判断
maxWidth
和maxHeight
是否都有定义。- 如果图片的宽度 (
width
) 或者高度 (height
) 超过了指定的最大值,则需要进行缩放。- 计算缩放比例 (
ratio
),使用Math.min
函数来确定应用于宽度和高度的最小比例,以确保图片在两个维度上都适应指定的最大限制。- 将原始的宽度和高度乘以这个比例,从而使图片缩放到适当的大小。
- 如果只有
maxWidth
有定义,并且图片宽度 (width
) 超过了maxWidth
,则需要根据比例调整高度 (height
),以确保图片不会超过指定的最大宽度。- 如果只有
maxHeight
有定义,并且图片高度 (height
) 超过了maxHeight
,则需要根据比例调整宽度 (width
),以确保图片不会超过指定的最大高度。
代码如下:
export function compressImage(options: any) {
const { file, photoType, quality = 10, maxWidth, maxHeight } = options;
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = () => {
const canvas = document.createElement('canvas');
let width = image.width;
let height = image.height;
if (maxWidth && maxHeight) {
if (width > maxWidth || height > maxHeight) {
const ratio = Math.min(maxWidth / width, maxHeight / height);
console.log(ratio, 'ratio');
width *= ratio;
height *= ratio;
}
} else if (maxWidth && width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
} else if (maxHeight && height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
if (!ctx) {
reject(new Error('NOT 2D canvas'));
return;
}
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
canvas.toBlob(
(blob) => {
if (!blob) {
reject(new Error('err blob'));
return;
}
if (photoType === 'blob') {
resolve(blob);
} else if (photoType === 'file') {
const compressedFile = new File([blob], file.name, { type: blob.type });
resolve(compressedFile);
} else {
reject(new Error('err type'));
}
},
file.type,
quality / 10
);
};
image.onerror = () => {
reject(new Error('onerrr'));
};
image.src = URL.createObjectURL(file);
});
}