使用Canvas实现质量压缩
2024 年 5 月 7 日 星期二(已编辑)
/ ,
15
摘要
这段代码实现了图片压缩功能,通过将图片进行重绘来改变其尺寸和质量,从而达到压缩图片的效果。压缩后的图片文件将以JPEG格式保存,并返回给调用者。
这篇文章上次修改于 2024 年 5 月 9 日 星期四,可能部分内容已经不适用,如有疑问可询问作者。
import {message, UploadFile} from 'antd';
const compressImage = async (file: File, maxWidth: number, maxHeight: number, quality: number) => {
return new Promise<File>((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event: ProgressEvent<FileReader>) => {
const target = event.target;
if (target && target.result && typeof target.result === 'string') {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
//判断是否超过最大宽高
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
canvas.width = width;
canvas.height = height;
//Canvas开始重新绘制
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob((blob) => {
if (blob) {
const compressedFile = new File([blob], file.name, {
type: 'image/jpeg',
lastModified: Date.now(),
});
resolve(compressedFile);
} else {
reject(new Error('无法获取图像数据'));
}
}, 'image/jpeg', quality);
} else {
reject(new Error('无法获取画布上下文'));
}
};
mg.src = target.result;
} else {
reject(new Error('无效的文件格式'));
}
};
reader.readAsDataURL(file);
});
};
const ImageCompression = async (file: File | UploadFile) => {
const MAX_WIDTH = 800; //最大宽度
const MAX_HEIGHT = 600; //最大高度
const COMPRESSION_QUALITY = 0.7; //压缩系数
try {
const compressedFile = await compressImage(file as File, MAX_WIDTH, MAX_HEIGHT, COMPRESSION_QUALITY);
return compressedFile;
} catch (error) {
message.error('图片压缩失败');
throw error;
}
};
export default ImageCompression;