当前位置: 首页 > 工具软件 > PHPCI > 使用案例 >

百度AI模板 phpCI框架 通过access_token获取 人脸识别信息

古明煦
2023-12-01
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//百度AI模板    phpCI框架  通过access_token获取 人脸识别信息
class  Yuansheng extends CI_Controller{
    function __construct(){
        parent::__construct();
        $this->load->helper(array('form', 'url','base','captcha','curl')); //鍔犺浇杈呭姪鍑芥暟
        $this->load->model('db_model');
        $this->load->library('session');
      
    }
    
    public function index() {
         $access=$this->Access_token();
         // var_dump($access);
      $token=$access['access_token'];
      $url_imag='http://photo13.zastatic.com/images/photo/16736/66942326/1407173325262_9.jpg';
      $this->detect($token,$url_imag);
	}
    function detect($token,$url_imag){
        // $token = '[调用鉴权接口获取的token]';
$url = 'https://aip.baidubce.com/rest/2.0/face/v1/detect?access_token=' . $token;
$img = file_get_contents($url_imag);
$img = base64_encode($img);
$bodys = array(
    'max_face_num' => 5,
    'face_fields' => "age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities",
    'image' => $img
);
$res =$this->request_post($url, $bodys);
 $res=json_decode($res,true);
// var_dump($res);
// var_dump($res["result"]);
//echo $res["result"][0]["age"];
echo "年龄:".$res["result"][0]["age"] ;
    }
    function request_post($url = '', $post_data = '') {
        $ch =curl_init();
        $timeout = 300;
        curl_setopt($ch, CURLOPT_URL, $url);
        //curl_setopt($ch, CURLOPT_REFERER, "http://api.dushiyangguan.com/"); 

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $res = curl_exec($ch);


        if (curl_errno($ch)) {
            echo 'Curl error: ' . curl_error($ch);
        }


        curl_close($ch);

        return $res; 
  
    }     

    
    function Access_token(){
    $url = 'https://aip.baidubce.com/oauth/2.0/token';
    $post_data['grant_type']       = 'client_credentials';
    $post_data['client_id']      = 'DOj8e2bMGxBpTWYQEj5cyrzA';
    $post_data['client_secret'] = 'ANVVv2wFstoSwx02YKlGqW2bDo7q2jMi';
    $o = "";
    foreach ( $post_data as $k => $v ) 
    {
        $o.= "$k=" . urlencode( $v ). "&" ;
    }
    $post_data = substr($o,0,-1);
    
    $res = $this->request_post($url, $post_data);

    // var_dump($res);
return  json_decode($res,true); //注意需要转换一下
    }
}




    

 类似资料: