使用js压缩图片后转为二进制上传

1.封装压缩图片方法

 
methods:{
    compress(img) {
        var url = null;
        var canvas = document.createElement("canvas");
        var scale = img.height / img.width;
        canvas.width = 720;
        canvas.height = 720 * scale;
        var ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        url = canvas.toDataURL("image/jpeg");
        return url; //这里返回的是一个base64
    }
}

2.封装base64转二进制方法


methods:{
     dataURItoBlob(dataURI) {
  
        let byteString = window.atob(dataURI.split(',')[1])
        let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
        let ab = new ArrayBuffer(byteString.length)
        let ia = new Uint8Array(ab)
        for (let i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i)
        }
        return new window.Blob([ab], {type: mimeString})
    }
}

3.实际应用

<input  @change='add_img' type="file" />

    add_img(event) {
        let file = event.target.files[0]
        if (/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(event.target.value)) {
          this.uploadLoading=true
          let reader = new FileReader()
          let self = this
          reader.readAsDataURL(file)
          let img = new Image;
          reader.onload = function (e) {
            img.src = this.result;
            img.onload = function () {
              let base = e.target.result
              let fileItem = file
             
              if( self.isCompress){ //根据自己的需求判断是否需要压缩
                base = self.compress(img)  //这里调用此前封装的要是图片方法,返回的是一个base64.
                fileItem =  self.dataURItoBlob(base) //在这里将base64转为二进制.
              }
              let formdata = new window.FormData()
              formdata.append('file', fileItem)
              utilsApi.upload(formdata).then(res => {
                 console.log('上传成功')
                self.uploadLoading=false
              }).catch(e => {
                event.target.value = ''
                self.uploadLoading=false
              });
            }
          }
        } else {
          this.$notify.error({
            title: '上传图片错误',
            message: '请上传gif|jpg|jpeg|png|GIF|JPG|PNG格式图片'
          })
        }
      }

上一篇:百度编辑器(UEditor)上传图片word


下一篇:CTFshow 命令执行 web32