vue2上传图片image-conversion压缩

项目中涉及上传图片,如果大体积的一般都需要压缩,这里我使用image-conversion来压缩

其实在npm中使用已经说得很明白了,我这里记录一下跟element ui上传组件配合使用

1、安装image-conversion
复制代码
 npm i image-conversion --save
2、引入使用
2.1、这里配合element ui的上传组件配合使用
复制代码
<el-upload
                    class="upload-demo"
                    style="
                      display: inline-block;
                      margin-left: 3%;
                      vertical-align: top;
                    "
                    enctype="multipart/form-data"
                    :action="baseUrl"
                    :headers="headers"
                    name="file"
                    :data="loadData"
                    :before-upload="beforeUpload"
                    :on-success="uploadSuccess"
                    list-type="picture"
                    :show-file-list="showFileList"
                  >
                    <el-button
                      size="small"
                      style="
                        width: 90px;
                        backgoound: white;
                        border: 1px solid rgba(73, 128, 255, 1);
                        color: rgba(73, 128, 255, 1);
                      "
                      class="upload-btn"
                      >点击上传</el-button
                    >
                    <div slot="tip" class="el-upload__tip">
                      只能上传jpg/jpeg/png文件,
                    </div>
                    <div slot="tip" class="el-upload__tip">且不超过30Mb</div>
                  </el-upload>

上传前方法中处理压缩逻辑,压缩质量参数,我单独封装了

复制代码
import * as imageConversion from 'image-conversion';
//压缩质量
export function getCompressionQuality(isLtSize,imgType) {
  if (isLtSize < 3) {
      return 0.93;
    } else if (isLtSize >= 3 && isLtSize < 5) {
      return 0.90;
    } else if (isLtSize >= 5 && isLtSize < 10) {
      return 0.80;
    } else if (isLtSize >= 10 && isLtSize < 20) {
      return 0.70;
    } else if (isLtSize >= 20 && isLtSize < 30) {
      return 0.60;
    }
  return 0.90;
}
//压缩逻辑
export function compressImage(file, quality) {
  return new Promise((resolve, reject) => {
    imageConversion.compress(file, quality)
      .then((res) => {
        resolve(res);
        console.log('压缩后体积', res.size / (1024 * 1024));
      })
      .catch((error) => {
        reject(error);
      });
  });
}

import { getCompressionQuality, compressImage } from '@/utils/compressionUtils.js';
beforeUploadLoad(file) {
      return this.processImage(this, file, this.loadData, false);
    },
    //上传图片前压缩图片
    processImage(that, file, uploadData, isUnload) {
      const imgType = file.type.toUpperCase();
      const isLt30M = file.size / 1024 / 1024 < 30;
      const isLt2M = file.size / 1024 / 1024 < 2;
      const isLtSize = file.size / 1024 / 1024;
      console.log('压缩前图片size', file.size / 1024 / 1024);
      uploadData.isCompressed = 0
      if (
        imgType !== "IMAGE/JPG" &&
        imgType !== "IMAGE/JPEG" &&
        imgType !== "IMAGE/PNG"
      ) {
        that.$message.error("请上传正确格式的图片");
        return false;
      }
      if (!isLt30M) {
        that.$message.error("上传的图片不能超过30Mb");
        return false;
      }
      //压缩质量
      const quality = getCompressionQuality(isLtSize,imgType);
      //大于2M走压缩逻辑
      if (!isLt2M) {
        console.log('quality', quality);
        return compressImage(file, quality)
          .then(compressedFile => {
            return compressedFile;
          })
          .catch(err => {
            console.error('Image compression error:', err);
            return file;
          });
      }
    },

这样上传图片时压缩就可以了,大家可以根据项目压缩质量需求来调整压缩参数

相关推荐
Warren9813 分钟前
Lua 脚本在 Redis 中的应用
java·前端·网络·vue.js·redis·junit·lua
mCell35 分钟前
JavaScript 运行机制详解:再谈 Event Loop
前端·javascript·浏览器
帧栈5 小时前
开发避坑指南(27):Vue3中高效安全修改列表元素属性的方法
前端·vue.js
max5006005 小时前
基于桥梁三维模型的无人机检测路径规划系统设计与实现
前端·javascript·python·算法·无人机·easyui
excel5 小时前
使用函数式封装绘制科赫雪花(Koch Snowflake)
前端
萌萌哒草头将军6 小时前
Node.js v24.6.0 新功能速览 🚀🚀🚀
前端·javascript·node.js
持久的棒棒君7 小时前
启动electron桌面项目控制台输出中文时乱码解决
前端·javascript·electron
小离a_a8 小时前
使用原生css实现word目录样式,标题后面的...动态长度并始终在标题后方(生成点线)
前端·css
郭优秀的笔记8 小时前
抽奖程序web程序
前端·css·css3
尚学教辅学习资料9 小时前
Vue3从入门到精通: 4.5 数据持久化与同步策略深度解析
vue·数据持久化