vue 通过 image-conversion 实现图片压缩

简介

vue项目中,上传图片时如果图片很大,通过 image-conversion 压缩到指定大小

1. 安装依赖

复制代码
npm i image-conversion --save

2. 引用

复制代码
import * as imageConversion from 'image-conversion'

3. 使用

复制代码
const newFile = new Promise((resolve) => {
	// 压缩到500KB,这里的500就是要压缩的大小,可自定义
	imageConversion.compressAccurately(file, 500).then(res => {
	  resolve(res)
	}).finally(() => {
	  console.log('将图片文件压缩到了500kb')
	})
})

4. 实际场景应用

复制代码
<!--  上传按钮  -->
<el-upload
  action=""
  class="upload"
  multiple
  accept=".png, .jpg, .jpeg"
  :before-upload="beforeDocumentUpload"
  :http-request="beforeAvatarUpload"
  :on-preview="handlePictureCardPreview"
  :before-remove="handlerBeforeRemove"
  :file-list="pictureList"
  :limit="10"
  :on-exceed="handleExceed"
  list-type="picture-card"
>
  <i class="el-icon-plus" />
</el-upload>
<!--  预览大图 -->
<el-dialog :visible.sync="imgVisible" :append-to-body="true">
  <img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>

methods:

复制代码
methods: {
	// 上传前
    beforeDocumentUpload(file) {
      const size = file.size / 1024 / 1024
		
	  // 上传的图片大小不能超过10M
      if (size > 10) {
        this.$message.warning('文件大小不能超过10M!')
        return false
      }
      const extension = this.getFileType(file)
		
	  // 只支持 png, jpg, jpeg 格式
      if (!['png', 'jpg', 'jpeg'].includes(extension)) {
        this.$message.warning('只能上传png、jpg、jpeg格式文件!')
        return false
      }
      
      // 大于0.5M压缩成0.5M
      if (size > 0.5) {
        const loading = this.$loading({
          lock: true,
          text: '加载中'
        })
        // 压缩
        const newFile = new Promise((resolve) => {
          // 压缩到500KB,这里的500就是要压缩的大小,可自定义
          imageConversion.compressAccurately(file, 500).then(res => {
            resolve(res)
          }).finally(() => {
            loading.close()
          })
        })
        console.log('newFIle', newFile)
        return newFile
      }
      return true
    },
    // 上传
    beforeAvatarUpload(file) {
      const self = this
      const reader = new FileReader()
      reader.readAsDataURL(file.file)
      reader.onload = function(e) {
        // const img_base64 = e.target.result
        // 自定义数组对象,传给后台的数据
        self.imgBase64Array.push({
          uid: file.file.uid,
          base64Str: file
          // base64Str: img_base64
        })
      }
    },
    // 预览大图
	handlePictureCardPreview(file) {
	  this.dialogImageUrl = file.url
	  this.imgVisible = true
	},
	// 删除图片
    handlerBeforeRemove(file, fileList) {
      this.imgBase64Array = this.imgBase64Array.filter((p) => p.uid !== file.uid)
    },
    handleExceed() {
      this.$message.warning('图片数量最多为10张')
    },
},
相关推荐
阿成学长_Cain17 小时前
Linux telinit 命令详解:运行级别切换|关机重启|系统维护一站式掌握
linux·运维·前端·网络
Patrick_Wilson18 小时前
最佳实践是有保质期的:从一次 CDN external 白屏事故说起
前端·性能优化·前端工程化
YHHLAI18 小时前
[特殊字符] Agent 智能体开发实战 · 第一课:Tool Use —— 让大模型自动干活
前端·人工智能
nuIl18 小时前
我把 5 个编码 Agent 塞进了一个 npm 包
前端·agent·claude
L-影18 小时前
FastAPI 静态文件:Web 页面的“固定展柜”与“加速引擎”
前端·fastapi
陪我去看海18 小时前
受够了 AI 写完代码留下一堆端口?我做了一个端口管理App!
前端·macos·vibecoding
Xuepoo18 小时前
我抛弃了 DOM,但保留了无障碍访问
前端
李明卫杭州18 小时前
Vue2 vs Vue3 的 h 函数:渲染函数完整迁移指南
前端
月光刺眼18 小时前
用LangChain 打造第一个 Agent:LLM 大脑与 Tool 手脚的完整闭环
javascript·人工智能·全栈
星栈18 小时前
LiveView 的认证系统:从登录到权限,我一开始以为有 `current_user` 就算完事了
前端·前端框架·elixir