微信小程式人臉識別
阿新 • • 發佈:2019-01-03
微信小程式中的人臉識別登入大大提高了使用者登入的安全性,所以人臉識別的技術應用的越來越廣泛了。下面我們就來看看在微信小程式中人臉識別技術該怎麼寫。
首先我們需要搭建一個前臺的簡單頁面,示例程式碼如下:
<camera device-position="front" flash="off" binderror="error" style="width: 100%; height: 300px;"></camera> <button type="primary" bindtap="takePhoto">刷臉登入</button> <image mode="widthFix" src="{{src}}"></image>
在TP框架中我們也需要寫大量的程式碼
public function login(){ $dir="./Uploads/temp/"; if (!file_exists($dir)) { mkdir($dir,0777,true); } $upload = new \Think\Upload();// 例項化上傳類 $upload->maxSize = 2048000 ;// 設定附件上傳大小 $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 設定附件上傳型別 $upload->rootPath = $dir; // 設定附件上傳根目錄 $upload->savePath = ''; // 設定附件上傳(子)目錄 $upload->autoSub=false; //上傳檔案 $info = $upload->uploadOne($_FILES['file']); if(!$info) {// 上傳錯誤提示錯誤資訊 return $this->ajaxReturn(array('error'=>true,'msg'=>$upload->getError()),JSON_UNESCAPED_UNICODE); }else{ // $this->ajaxReturn('上傳成功'); $file=$dir.$info['savepath'].$info['savename']; $image=base64_encode(file_get_contents($file)); $dirs=APP_PATH .'/face-sdk/'; require_once $dirs.'AipFace.php'; $APP_ID=''; $API_KEY=''; $SECRET_KEY=''; $client = new \AipFace($APP_ID, $API_KEY, $SECRET_KEY); $options['liveness_control']='NORMAL'; $options['max_user_num']='1'; $ret=$client->search($image,'BASE64',$this->face_group(),$options); // echo json_encode($ret,JSON_UNESCAPED_UNICODE); // exit; if ($ret['error_code']==0) { $user=$ret['result']['user_list'][0]; $no=$user['user_id']; $score=$user['score']; if (!empty($no)) { $data=M('student')->field('no,name,sex')->where("no='{$no}'")->find(); if ($data) { $data['score']=$score; // if ($score>95) { // echo "姓名:".$data['name']; // }else{ echo json_encode($data,JSON_UNESCAPED_UNICODE); // } }else{ echo "本地資料庫沒有該學生,百度雲庫資訊:個人資訊:{$no},分值:{$score}"; } } }else{ echo "活體檢測失敗".json_encode($ret,JSON_UNESCAPED_UNICODE); } } }
然後我們在微信開發者工具中寫一些js的程式碼,就可以實現人臉識別的功能了
takePhoto() { const ctx = wx.createCameraContext() ctx.takePhoto({ quality: 'high', success: (res) => { this.setData({ src: res.tempImagePath, }) // console.log(src), wx.showLoading({ title: '正在核驗身份', }) this.setData({ logindisabled: true }); wx.uploadFile({ url: '', //僅為示例,非真實的介面地址 filePath: res.tempImagePath, name: 'file', // formData: { // 'user': 'test' // }, success: (res) => { wx.hideLoading(); var data = res.data; this.setData({ logindisabled: false }); var data = res.data console.log(data); wx.showModal({ title: '提示', content: data, showCancel: false }) //do something } }) } }) },
這樣一個簡單的人臉識別功能就完成了。