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

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

相关推荐
子兮曰5 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰5 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万5 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝5 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
千里马学框架5 天前
一起学 Android 14:ShellTransition 屏幕旋转过程深度剖析
android·智能手机·性能优化·framework·性能·屏幕旋转·rotation
三十而立洋5 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁5 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
汉堡大王95275 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端
梦想很大很大5 天前
从运行事实到回归证据:Workrun 的 Telemetry 与 Evaluation 实践
前端·人工智能·后端
计算机魔术师5 天前
Meta Muse agent 接入 Shopify 的 Shop Pay 实现代理式购物
前端