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;
          });
      }
    },

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

相关推荐
天渺工作室7 小时前
实现一个adblock/adblock plus等浏览器广告拦截器检测插件
前端·javascript
阳光是sunny7 小时前
Vue 项目怎么做用户行为全链路监控?轻量插件方案详解
前端·面试·架构
ZhengEnCi7 小时前
Q04-Vite禁用CSS代码分割-解决生产环境样式加载顺序混乱问题
前端·vue.js·vite
九酒8 小时前
AI Agent 开发踩坑记:口播功能非得用 APP 原生实现吗?
前端·人工智能·agent
Jackson__9 小时前
做了一段时间的AI coding后,我终于搞清了 CLI 和 MCP 的区别
前端·agent·ai编程
IT_陈寒11 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
用户479492835691512 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
薛定喵的谔13 小时前
我开源了一个精致的 Next.js 博客模板:Skyplume
前端·前端框架·next.js
张龙68714 小时前
构建生产级 AI Agent:工具调用与记忆架构实战指南
前端
kyriewen15 小时前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js