手机端上传照片压缩功能canvas

手机上传照片拍摄的照片像素很高需要压缩后上传,移动端前端压缩照片的方法一般是用canvas,然后转换成base64或者blob,发送后台。

 <div class="img-btn1">
      <img class="img" src="@images/camore.png" alt v-if="imgShow1" />
      <img class="imgs" src alt id="newImage1" v-else />
      <input class="fileInpBtn" type="file" @change="showPicture1($event)" accept="image/*" multiple/>
  </div>

压缩方法

  showPicture1(e) {
      if (e.target.files[0]) {
        this.imgShow1 = false;
        this.$vux.loading.show({
          text: "验证中..."
        });
        // 获取上传文件的路径,并赋给img标签
        this.$nextTick(() => {
          document.getElementById("newImage1").src = window.URL.createObjectURL(
            e.target.files[0]
          );
        });
        // let formData = new FormData();
        // formData.append("file", e.target.files[0]); // 传文件
        // formData.append("cardSide", "FRONT");
        // formData.append('openid', getSStore('openid'));
        var file = e.target.files[0];
        let size2 = Math.floor(file.size / 1024);
        let that = this;
        if (size2 > 1024) {
          // 大于2M,进行压缩上传
          this.photoCompress(file, function(filebase) {
            var params = {
              file: filebase,
              cardSide: "FRONT"
            };
            that.uploadImg(params);
          });
        } else {
          var reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => {
            var imgcode = reader.result;
            // 读取到的图片base64 数据编码 将此编码字符串传给后台即可
            var params = {
              file: imgcode.replace(new RegExp("\\+", "gm"), "%2B"),
              cardSide: "FRONT"
            };
            this.uploadImg(params);
          };
        }
      }
    },
photoCompress: function(file, callback) {
      var that = this;
      var ready = new FileReader();
      /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容. */
      ready.readAsDataURL(file);
      ready.onload = function() {
        var re = this.result;
        var img = new Image();
        img.src = re;
        img.onload = function() {
          var that = this;
          // 默认按比例压缩
          var w = 400;
          var h = (w * img.height) / img.width;
          var quality = 0.7; // 默认图片质量为0.7
          // 生成canvas
          var canvas = document.createElement("canvas");
          var ctx = canvas.getContext("2d");
          // 创建属性节点
          var anw = document.createAttribute("width");
          anw.nodeValue = w;
          var anh = document.createAttribute("height");
          anh.nodeValue = h;
          canvas.setAttributeNode(anw);
          canvas.setAttributeNode(anh);
          ctx.drawImage(that, 0, 0, w, h);
          //也可以把压缩后的图片转blob格式用于上传
                // canvas.toBlob((blob)=>{
                //     console.log(blob)
                //     //把blob作为参数传给后端
                // }, 'image/jpeg', 0.92)
          // quality值越小,所绘制出的图像越模糊
          var base64 = canvas.toDataURL("image/jpg", quality);
          // 正则替换哈 imgData 为base64字符串
			base64.replace(/^data:image\/\w+;base64,/, "");
         // base64中,加号(+)是base64编码的一部分,如果将+号转变为空格,就会导致解密失败,所以要转换成%2b。
          var filebase = base64.replace(new RegExp("\\+", "gm"), "%2B");
          callback(filebase);// 回调函数返回的值
        };
      };
    },
    uploadImg(params) {
      this.$http
        .uploadPost("/fileManager/fileUploadOcr", params)
        .then(res => {
          this.$vux.loading.hide();
          if (res.code === 0) {
            if (this.$route.query.action === "personalCenter") {
              this.$http.post("/customer/info", {}).then(response => {
                let identityNo = response.body.info.identityNo;
                if (identityNo !== res.body.IdNum) {
                  this.$vux.alert.show("身份证信息不匹配,请重新上传!");
                  this.clearData();
                  this.imgShow1 = true;
                  document.getElementById("newImage1").src = "";
                } else {
                  this.identifyInfo.name = res.body.Name;
                  this.identifyInfo.Sex = res.body.Sex;
                  this.identifyInfo.Birth = res.body.Birth;
                  this.identifyInfo.IdNum = res.body.IdNum;
                }
              });
            } else {
              this.identifyInfo.name = res.body.Name;
              this.identifyInfo.Sex = res.body.Sex;
              this.identifyInfo.Birth = res.body.Birth;
              this.identifyInfo.IdNum = res.body.IdNum;
            }
          } else {
            this.clearData();
            this.imgShow1 = true;
            document.getElementById("newImage1").src = "";
          }
        })
        .catch(res => {
          this.clearData();
          this.imgShow1 = true;
          document.getElementById("newImage1").src = "";
        });
    },

在这里插入图片描述
参考网址:https://blog.csdn.net/huangpb123/article/details/80560980

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值