在使用百度的人脸识别的时候有几个需要注意的地方(主要是一些报错)
前提说一下,是在vue框架下进行的百度人脸识别接口的调用
vue项目,在reader.onload函数中拿不到this,无法将数值传递到全局
解决办法: 遇到这种问题的话,在reader.onload函数外层用 let that = this 来记录一下this,这样在里面使用that就可以拿到this了
在调百度的接口的时候遇到报错,信息为: " errorcode":222200,"errormsg":"request body should be json format"。
解决办法: 当时我的data 直接就是一个对象,只要将对象外面包裹一个中括号变成数组就可以了,如下
let data = {
                      image: tempImgData,
                      image\_type: 'BASE64',
                    }变成如下
let data = [{
                      image: tempImgData,
                      image\_type: 'BASE64',
                    }]参数格式调好了,再次调用接口,发现又报一个错: image check fail,错误码222203。这个问题是因为传入的参数中的base64格式的图片有图片头( data:image/jpg;base64)
解决办法: 用这个代码去掉图片头
base64Img.replace(/^data:image\/\w+;base64,/, "")
附上这个调取人脸识别的整个函数
<input type="file" @change='getImgUrl($event)' id="ImgUrl">
// 拿到上传图片的信息
    getImgUrl(e) {
      // console.log(e.target.files\[0\])
      let data = e.target.files\[0\]
      // 图片转base64
      this.changeImg(data)
    },
    // 图片base64转换
    changeImg(file) {
      let that = this
      var reader = new FileReader();
      var AllowImgFileSize = 2100000; //上传图片最大值(单位字节)( 2 M = 2097152 B )超过2M上传失败
      // var file = $("#image")\[0\].files\[0\];
      var imgUrlBase64;
      if (file) {
        //将文件以Data URL形式读入页面  
        imgUrlBase64 = reader.readAsDataURL(file);
        reader.onload = function (e) {
          //var ImgFileSize = reader.result.substring(reader.result.indexOf(",") + 1).length;//截取base64码部分(可选可不选,需要与后台沟通)
          if (AllowImgFileSize != 0 && AllowImgFileSize < reader.result.length) {
              alert( '上传失败,请上传不大于2M的图片!');
              return;
          }else{
            // imgData.replace(/^data:image\\/\\w+;base64,/, "");
            //执行上传操作
            document.getElementById('showImg').src = reader.result
            let tempImgData = reader.result.replace(/^data:image\\/\\w+;base64,/, "")    // 去掉base64前面的图片头
            let data = [{
              image: tempImgData,
              image\_type: 'BASE64',
            }]
            // 调取百度接口,进行人脸识别
            that.axios.post('/info/rest/2.0/face/v3/faceverify?'+'access\_token='+that.getedToken, data,
            ).then( res => {
              console.log(res)
            }).catch( err => {
              console.log(err)
            })
          }
        }
      }
    } 
             
             
             
             
            