目录
一、安装
npm install compressorjs
或
yarn add compressorjs
官方文档:compressorjs - npm (npmjs.com)
二、编写工具类
javascript
/**
* @author Dragon Wu
* @since 2024/8/4 12:23
* 图片压缩工具
*/
import Compressor from 'compressorjs';
// 压缩图片方法 (中间件)
export function compressor(file: File, defaultQuality: number = 0.6) {
console.log('压缩前: ', (file.size / 1024 / 1024).toFixed(1), 'M');//控制台打印图片大小
const filesize = (file.size / 1024 / 1024).toFixed(1);
let quality = defaultQuality;
if (filesize < 0.8) { //这里可以设置自己的压缩规则
quality = 1;
} else if (filesize < 1) {
quality = 0.8;
} else if (filesize < 1.5) {
quality = 0.7;
} else if (filesize < 2) {
quality = 0.5;
} else if (filesize < 3) {
quality = 0.33;
} else if (filesize < 4) {
quality = 0.25;
} else if (filesize < 5) {
quality = 0.2;
} else if (filesize < 8) {
quality = 0.125;
} else if (filesize < 10) {
quality = 0.1;
} else {
return new Promise((resolve, reject) => {
reject({
msg: '图片不能超过10M'
})
});
}
console.log('压缩比例: ', quality);
return new Promise((resolve) => {
new Compressor(file, {
quality: quality,
success(result: File | Blob) {
console.log('压缩后: ', (result.size / 1024 / 1024).toFixed(1), 'M');
if (result instanceof Blob) {
//@ts-ignore
result = new File([result], "f" + (result?.name as string).slice(-8), {type: result.type})
}
resolve(result);
},
error(err) {
// 压缩报错的话 返回原图片
resolve(file);
},
});
});
}
三、获取压缩后的File对象
javascript
const handleBeforeUpload = (file: FileType) => {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.warning('只能上传JPG/PNG格式!').then();
}
const isLt2M = file.size / 1024 / 1024 < 10;
if (!isLt2M) {
message.warning('图片不得超过10MB!').then();
}
compressor(file).then(res => {
if (isJpgOrPng && isLt2M) {
onChange(res)
}
})
return false;
}
四、测试效果
可以看到源图片已经被压缩了,这样处理后再提交至服务器就能节省带宽,提高前端加载效率了,注意质量数值设置的过小图片过大可能导致图片失帧。
总结到此!