vue+element-ui upload图片上传前进行压缩

最近项目需要实现一个需求,用户上传图片时,进行图片压缩,长宽超过2000,需要压缩到400k,2000宽高.在git上找到一个不错的方法,把实现方法总结一下:

安装image-conversion包

npm install --save image-conversion

template

<template>
  <div class="select_invoice">
    <el-upload
      class="upload-demo" :multiple="true" :action="uploadPath" :data="uploadData" accept="bmg,.png,.jpg,.jpeg" :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="hanldeError" multiple
      :limit="20">
      <el-button size="small" type="primary">添加图片</el-button>
    </el-upload>
  </div>
</template>

 

压缩的方法放在before-upload中,这个方法可以接受一个promise,提一下,最好下载新版本的element-UI,以前的旧版本可能不支持返回promise

  // 引入image-conversion
import imageConversion from 'image-conversion'
 methods: { 
// 第一种,不考虑图片长宽,只考虑图片大小的情况,图片超过4M就压缩
 beforeUpload (file) { return new Promise((resolve, reject) => {
        let isLt2M = file.size / 1024 / 1024 < 4 // 判定图片大小是否小于4MB
        if (isLt2M) {
          resolve(file)
        }
        console.log(file) // 压缩到400KB,这里的400就是要压缩的大小,可自定义
        imageConversion.compressAccurately(file, 400).then(res => { // console.log(res)
         resolve(res)
        })
      })
    }, 
//第二种,图片大小超过4M,长度超过2000就压缩
 beforeUpload2 (file) { // 图片不大于4m,宽度不大于2000
      return new Promise((resolve, reject) => {
        let _URL = window.URL || window.webkitURL
        let isLt2M = file.size / 1024 / 1024 > 4 // 判定图片大小是否小于4MB
        // 这里需要计算出图片的长宽
        let img = new Image()
        img.onload = function () {
          file.width = img.width // 获取到width放在了file属性上
          file.height = img.height // 获取到height放在了file属性上
          let valid = img.width > 2000 // 图片宽度大于2000
          // console.log(11, file)
          // 这里我只判断了图片的宽度,compressAccurately有多个参数时传入对象
          if (valid || isLt2M) {
            imageConversion.compressAccurately(file, {
              size: 400,
              width: 2000 }).then(res => { // console.log(33, res)
               resolve(res)
            })
          } else resolve(file)
        } // 需要把图片赋值
        img.src = _URL.createObjectURL(file)
      })
    },
  } </script>

这样就实现了图片的自动压缩功能,这个组件还有一些其他功能,使用的时候如果有其他需求,可以看下文档https://github.com/WangYuLue/image-conversion

 

 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值