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张')
    },
},
相关推荐
bin91531 小时前
DeepSeek 助力 Vue 开发:打造丝滑的复制到剪贴板(Copy to Clipboard)
前端·javascript·vue.js·ecmascript·deepseek
晴空万里藏片云2 小时前
elment Table多级表头固定列后,合计行错位显示问题解决
前端·javascript·vue.js
曦月合一2 小时前
html中iframe标签 隐藏滚动条
前端·html·iframe
奶球不是球2 小时前
el-button按钮的loading状态设置
前端·javascript
kidding7233 小时前
前端VUE3的面试题
前端·typescript·compositionapi·fragment·teleport·suspense
无责任此方_修行中4 小时前
每周见闻分享:杂谈AI取代程序员
javascript·资讯
Σίσυφος19005 小时前
halcon 条形码、二维码识别、opencv识别
前端·数据库
学代码的小前端5 小时前
0基础学前端-----CSS DAY13
前端·css
dorabighead6 小时前
JavaScript 高级程序设计 读书笔记(第三章)
开发语言·javascript·ecmascript
css趣多多6 小时前
案例自定义tabBar
前端