vue 下h5 图片上传压缩处理(部分主要代码)

参考文章:
https://blog.csdn.net/rmnctn/article/details/79452709
https://www.cnblogs.com/apanly/p/5731086.html



addPic: function (e) {
        this.$refs.input.click()

        //ios 下不晓得为何还要再执行一次
        if (this.$isIos) {
          this.$refs.input.click()
        }
        return false
      },
      onFileChange: function (e) {
        var that = this
        var files = e.target.files || e.dataTransfer.files
        if (!files.length) return

        var reader = new FileReader()
        reader.onload = function (e) {
          //base64 图片信息
//          alert(this.result);
        // 自已处理
          that.compress(this.result)
        }
        reader.readAsDataURL(files[0])

        //使用 lrz 进行图片压缩处理
//        this.createImage(files, e)
      },

      compress: function (res) {
        var that = this
        var img = new Image(),
          maxH = 300

        img.onload = function () {
          var cvs = document.createElement('canvas'),
            ctx = cvs.getContext('2d')

          if (img.height > maxH) {
            img.width *= maxH / img.height
            img.height = maxH
          }
          cvs.width = img.width
          cvs.height = img.height

          ctx.clearRect(0, 0, cvs.width, cvs.height)
          ctx.drawImage(img, 0, 0, img.width, img.height)
          var dataUrl = cvs.toDataURL('image/jpeg', 1)

          that.imgUrls.push(dataUrl)

          // 上传略
          that.upload(dataUrl)
        }

        img.src = res
      },

      upload: function (image_data) {
        /*这里写上次方法,图片流是base64_encode的*/
      },

      createImage: function (file, e) {
        let vm = this
        lrz(file[0], {
          width: 680,
        }).then(function (rst) {
          vm.imgUrls.push(rst.base64)
          return rst
        }).always(function () {
          // 清空文件上传控件的值
          e.target.value = null
        })
      },

你可能感兴趣的:(vue 下h5 图片上传压缩处理(部分主要代码))