前端上传图片并初步压缩图片

上传图片和压缩

前端处理用户图片, 控制上传图片的大小, 减轻服务器流量压力

  • 首先通过input获取图片
<input type="file" accept="image/*" alt="图片" multiple @change="changeImage">
  • 获取所有图片数据并添加到一个数组中
	let file = e.target.files
    let arr = []
     for (let i = 0; i < file.length; i ++) {
       arr.push(file[i])
     }
  • 通过遍历判断图片原始文件的大小(这里大小是字节), 来选择是否压缩
  • 图片压缩功能实现有很多方法, 我在这里用的是lrz的压缩插件
  • 下载插件 :
npm i lrz -S
lrz( value , options).then(function(rst){...})

其中 value : 图片file数据
options : 是lrz插件的设置, 可以再里面设置 quality (压缩比例)
rst : 是插件返回的一个对象, 其中包括 压缩后的 base64格式

因为后台不接收base64格式的图片文件,所以下面进行了格式转换

	var blob = this.dataURLtoBlob(rst.base64)
	var newfile = this.blobToFile(blob, name)
	// newfile  就是最后转换好的格式了
  • 下面是完整的代码, 希望能给大家提供帮助
// 上传图片处理
    changeImage (e) {
      let file = e.target.files
      let arr = []
      for (let i = 0; i < file.length; i ++) {
        arr.push(file[i])
      }
      // console.log(file)
      var options = {
        quality: 0.1
      }
      arr.forEach(function(value,j){
        // this.imgList[i].img =  window.URL.createObjectURL(file[i])
        if (file.size > 1000000) {
          lrz( value , options).then(function(rst) {
            //成功时执行
            var blob = this.dataURLtoBlob(rst.base64)
            var newfile = this.blobToFile(blob, name)
            this.imgList.push ({
              img: newfile,
              img64: rst.base64,
              index: this.imgLength
            } )
            this.imgLength ++
          }.bind(this)).catch(function(error) {
            //失败时执行
            console.log('失败', error)
          }).always(function() {
            //不管成功或失败,都会执行
          })
        } else {
          console.log(1)
          this.imgList.push ({
            img: value,
            img64: URL.createObjectURL(value),
            index: this.imgLength
          } )
          this.imgLength ++
        }
        
      }.bind(this))
      
    },
    //将base64转换为blob
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    //将blob转换为file
    blobToFile(theBlob, fileName) {
      theBlob.lastModifiedDate = new Date()
      theBlob.name = fileName;
      return theBlob;
    },
  },
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值