在使用百度的人臉識別的時候有幾個需要注意的地方(主要是一些報錯)

前提說一下,是在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)

            })

          }

        }

      }

    }

希望能幫到一些童鞋

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章