百度雲人臉識別- 獲取token+輸出圖片人臉檢測的資訊
阿新 • • 發佈:2019-01-02
使用thinkPHP框架 來獲取人臉識別的token。
在application中的common中新建一個function.php
/獲取access_token function request_post($url = '', $param = '') { if (empty($url) || empty($param)) { return false; } $postUrl = $url; $curlPost = $param; $curl = curl_init();//初始化curl curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定網頁 curl_setopt($curl, CURLOPT_HEADER, 0);//設定header curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求結果為字串且輸出到螢幕上 curl_setopt($curl, CURLOPT_POST, 1);//post提交方式 curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curl, CURLOPT_SSLVERSION, 1); $data = curl_exec($curl);//執行curl curl_close($curl); return $data; } function access_token(){ $file=__DIR__.'\access_token'; if(file_exists($file)){ $str=file_get_contents($file); try{ $arr=json_decode($str,true); if (is_array($arr)) { $totime=$arr['totime']; if ($totime>time()) { return $arr['access_token']; exit; } } }catch(Exception $e){ } } $apikey="你的apikey"; $secretkey="你的secretkey"; $url = 'https://aip.baidubce.com/oauth/2.0/token'; $post_data['grant_type'] = 'client_credentials'; $post_data['client_id'] = $apikey; $post_data['client_secret'] = $secretkey; $o = ""; foreach ( $post_data as $k => $v ) { $o.= "$k=" . urlencode( $v ). "&" ; } $post_data = substr($o,0,-1); $res = request_post($url, $post_data); $arr=json_decode($res,true); if (isset($arr['access_token']) && isset($arr['expires_in'])) { $data['access_token']=$arr['access_token']; $data['totime']=time()+$arr['expires_in']-3600; file_put_contents($file, json_encode($data)); return $arr['access_token']; }else{ return false; } // var_dump($res); }
2. home的index控制器中
public function upload($id=''){ //上傳圖片 $upload = new \Think\Upload();// 例項化上傳類 $upload->maxSize = 3145728 ;// 設定附件上傳大小 $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 設定附件上傳型別 $upload->rootPath = './Uploads/'; // 設定附件上傳根目錄 $upload->savePath = ''; // 設定附件上傳(子)目錄 // 上傳單個檔案 $info = $upload->uploadOne($_FILES['file']); if(!$info) {// 上傳錯誤提示錯誤資訊 return $this->ajaxReturn(array('error'=>true,'msg'=>$upload->getErroe())); }else{// 上傳成功 獲取上傳檔案資訊 // echo $info['savepath'].$info['savename']; return $this->ajaxReturn(array('error'=>false,'msg'=>$info['savepath'].$info['savename'],'id'=>$id)); } }
//人臉檢測 public function facevalid(){ $token = access_token();//獲取的token // echo $token; $file = './Uploads/1.jpg'; if (!file_exists($file)) { die('檔案不存在!'); } $url="https://aip.baidubce.com/rest/2.0/face/v2/detect?access_token=".$token; $img=file_get_contents($file); $img=base64_encode($img); // echo $img; $bodys=array( 'max_face_num'=>5, 'face_fileds'=>"age,beauty,expression,faceshape,gender,galsses,landmark,race,qualities", 'image'=>$img ); $res=request_post($url,$bodys); echo $res;//輸出圖片檢測出的資訊 }