vue2上传图片image-conversion压缩

news/2024/7/10 1:43:59 标签: vue, 前端, 性能优化

项目中涉及上传图片,如果大体积的一般都需要压缩,这里我使用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;
          });
      }
    },

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


http://www.niftyadmin.cn/n/5333417.html

相关文章

前端开发1:HTML

在现代互联网的世界中&#xff0c;网页是我们与世界沟通的窗口。而HTML&#xff08;超文本标记语言&#xff09;作为网页的基石&#xff0c;扮演着至关重要的角色。在本篇博客中&#xff0c;我将向你介绍HTML的基本概念、语法以及一些常用的HTML标签。 HTML是什么&#xff1f;…

【驱动】I2C驱动分析(五)-模拟I2C驱动

在drivers/i2c/busses下包含各种I2C总线驱动&#xff0c;使用GPIO模拟I2C总线的驱动i2c-gpio.c&#xff0c;这里只分析i2c-gpio.c。 i2c-gpio.c它是gpio模拟I2C总线的驱动&#xff0c;总线也是个设备&#xff0c;在这里将总线当作平台设备处理&#xff0c;那驱动当然是平台设备…

一键式Excel分词统计工具:如何轻松打包Python脚本为EXE

一键式Excel分词统计工具&#xff1a;如何轻松打包Python脚本为EXE 写在最前面需求分析直接用Python打包为什么大&#xff1f;为什么要使用conda环境&#xff1f; 将Python脚本打包为一个独立的应用程序1. 编写Python脚本&#xff1a;初步功能实现2. 初步图形用户界面&#xff…

ac7811---硬件i2c---FM24C16D

1.使用硬件i2c&#xff0c;polling模式 2.从任意地址写任意长度数据暂未实现 3.FM24C16D的地址说明 #define I2C_READY_STATUS_TIMEOUT 400000 ///< I2C timeout value #define I2C_POLLING_SW (TRUE) #define I2C_SLAVE_ADDR (0xA0)//从机地址 #defi…

20240117-【UNITY 学习】增加墙跑功能和跳墙功能

替换脚本PlayerCam_01.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening;public class PlayerCam_02 : MonoBehaviour {// 视觉灵敏度参数public float sensX 400;public float sensY 400;// 视角垂直旋转角度限制publ…

五、基础篇 vue列表渲染

在v-for里使用对象用 v-for 把一个数组对应为一组元素 我们可以用 v-for 指令基于一个数组来渲染一个列表。v-for 指令需要使用 item in list形式的特殊语法&#xff0c;其中 list是源数据数组&#xff0c;而 item 则是被迭代的数组元素的别名。 <template><div clas…

【LeetCode】459. 重复的子字符串(简单)——代码随想录算法训练营Day09

题目链接&#xff1a;459. 重复的子字符串 题目描述 给定一个非空的字符串 s &#xff0c;检查是否可以通过由它的一个子串重复多次构成。 示例 1: 输入: s "abab" 输出: true 解释: 可由子串 "ab" 重复两次构成。 示例 2: 输入: s "aba" 输…

HarmonyOS—声明式UI描述

ArkTS以声明方式组合和扩展组件来描述应用程序的UI&#xff0c;同时还提供了基本的属性、事件和子组件配置方法&#xff0c;帮助开发者实现应用交互逻辑。 创建组件 根据组件构造方法的不同&#xff0c;创建组件包含有参数和无参数两种方式。 说明 创建组件时不需要new运算…