- 背景:elementui组件上传图片,图片大小超过2M则压缩图片
image-conversion安装方式
npm install image-conversion --save
image-conversion引用方式
const imageConversion = require("image-conversion")
import * as imageConversion from 'image-conversion';
import {compress, compressAccurately} from 'image-conversion';
image-conversions使用
- 在el-upload组件中:before-upload或者:on-change时间中写以下代码均可以
- imageConversion.compressAccurately返回一个Blob对象,如果要通过fomdata上传,则需要通过new File转换为 file类型
loadJsonFromFile(file, fileList) {
this.loadupload = fileList;
return new Promise((resolve, reject) => {
console.log('压缩前',file);
let isLt2M = file.size / 1024 / 1024 < 2 // 判定图片大小是否小于2MB
if (isLt2M) {
resolve(file)
}
// 压缩到1000KB,这里的1000就是要压缩的大小,可自定义
imageConversion.compressAccurately(file.raw, 1000).then(res => {
res = new File([res], file.name, { type: res.type, lastModified: Date.now() });
resolve(res);
this.loadupload[0].raw = res
})
})
},
const formData = new FormData();
formData.append('file', this.loadupload[0].raw)
image-conversions多个参数
imageConversion.compressAccurately(file.raw, {
size:1000,//图片压缩1000kb
width:500 //图片宽度压缩到500px
height: 200,
type: "image/jpeg",
}).then(res => {
res = new File([res], file.name, { type: res.type, lastModified: Date.now() });
resolve(res);
this.loadupload[0].raw = res
})