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张')
    },
},
相关推荐
Bellafu6661 小时前
selenium 常用xpath写法
前端·selenium·测试工具
blackorbird3 小时前
Edge 浏览器 IE 模式成攻击突破口:黑客借仿冒网站诱导攻击
前端·edge
谷歌开发者4 小时前
Web 开发指向标 | Chrome 开发者工具学习资源 (一)
前端·chrome·学习
名字越长技术越强4 小时前
Chrome和IE获取本机ip地址
前端
天***88964 小时前
Chrome 安装失败且提示“无可用的更新” 或 “与服务器的连接意外终止”,Chrome 离线版下载安装教程
前端·chrome
半梦半醒*4 小时前
zabbix安装
linux·运维·前端·网络·zabbix
大怪v5 小时前
【搞发🌸活】不信书上那套理论!亲测Javascript能卡浏览器Reader一辈子~
javascript·html·浏览器
清羽_ls5 小时前
React Hooks 核心规则&自定义 Hooks
前端·react.js·hooks
你的人类朋友5 小时前
“签名”这个概念是非对称加密独有的吗?
前端·后端·安全
西陵5 小时前
Nx带来极致的前端开发体验——任务缓存
前端·javascript·架构