• 背景:elementui组件上传图片,图片大小超过2M则压缩图片

image-conversion安装方式

  1. npm install image-conversion --save

image-conversion引用方式

  1. const imageConversion = require("image-conversion")
  1. import * as imageConversion from 'image-conversion';
  • or
  1. import {compress, compressAccurately} from 'image-conversion';

image-conversions使用

  • 在el-upload组件中:before-upload或者:on-change时间中写以下代码均可以
  • imageConversion.compressAccurately返回一个Blob对象,如果要通过fomdata上传,则需要通过new File转换为 file类型
  1. loadJsonFromFile(file, fileList) {
  2. this.loadupload = fileList;
  3. return new Promise((resolve, reject) => {
  4. console.log('压缩前',file);
  5. let isLt2M = file.size / 1024 / 1024 < 2 // 判定图片大小是否小于2MB
  6. if (isLt2M) {
  7. resolve(file)
  8. }
  9. // 压缩到1000KB,这里的1000就是要压缩的大小,可自定义
  10. imageConversion.compressAccurately(file.raw, 1000).then(res => {
  11. res = new File([res], file.name, { type: res.type, lastModified: Date.now() });
  12. resolve(res);
  13. this.loadupload[0].raw = res
  14. })
  15. })
  16. },
  • 上传图片参数
  1. const formData = new FormData();
  2. formData.append('file', this.loadupload[0].raw)

image-conversions多个参数

  1. imageConversion.compressAccurately(file.raw, {
  2. size:1000,//图片压缩1000kb
  3. width:500 //图片宽度压缩到500px
  4. height: 200,
  5. type: "image/jpeg",
  6. }).then(res => {
  7. res = new File([res], file.name, { type: res.type, lastModified: Date.now() });
  8. resolve(res);
  9. this.loadupload[0].raw = res
  10. })