基于TP3.2版人脸识别函数
获取人的脸部特征信息,得到一组特征数组
第一步,在百度开发者中心申请人脸识别接口,具体步骤查询百度
第二步,申请成功后记下API Key和Secret Key
第三步,在框架/Library/Org/Util/目录下建立Baidu.class.php代码如下<?php <br />
<br>
/**********************************************************<br>
*Author: dtnet(presdecoeur@gmail.com)<br>
*Time: 2014-6-5下午5:35:13<br>
*File: Bdauth.class.php<br>
**********************************************************/<br>
namespace Org\Util;<br>
<br>
class Baidu {<br>
public static $BD_OAUTH2_ENDPOINTS = array (<br>
'authorize' => 'https://openapi.baidu.com/oauth/2.0/authorize',<br>
'token' => 'https://openapi.baidu.com/oauth/2.0/token',<br>
'logout' => 'https://openapi.baidu.com/connect/2.0/logout',<br>
'face'=>'https://openapi.baidu.com/rest/2.0/media/v1/face/detect' <br>
);<br>
protected $clientId;<br>
protected $clientSecret;<br>
protected $redirectUri;<br>
public function __construct($clientId, $clientSecret) {<br>
$this->clientId = $clientId;<br>
$this->clientSecret = $clientSecret;<br>
}<br>
public function setRedirectUri($redirectUri) {<br>
if (empty ( $redirectUri )) {<br>
$redirectUri = $this->getCurrentUrl ();<br>
}<br>
$this->redirectUri = $redirectUri;<br>
return $this;<br>
}<br>
public function getRedirectUri() {<br>
return $this->redirectUri;<br>
}<br>
public function getLogoutUrl($accessToken, $next = '') {<br>
$params = array ('access_token' => $accessToken,'next' => $next ? $next : $this->getCurrentUrl () <br>
);<br>
return self::$BD_OAUTH2_ENDPOINTS ['logout'] . '?' . http_build_query ( $params, '', '&' );<br>
}<br>
public function getAuthorizeUrl($responseType = 'code', $scope = '', $state = '', $display = 'popup') {<br>
$params = array ('client_id' => $this->clientId,'response_type' => $responseType,'redirect_uri' => $this->redirectUri,'scope' => $scope,'state' => $state,'display' => $display <br>
);<br>
return self::$BD_OAUTH2_ENDPOINTS ['authorize'] . '?' . http_build_query ( $params, '', '&' );<br>
}<br>
public function getAccessTokenByAuthorizationCode($code)<br>
{<br>
$params = array(<br>
'grant_type' => 'authorization_code',<br>
'code' => $code,<br>
'client_id' => $this->clientId,<br>
'client_secret' => $this->clientSecret,<br>
'redirect_uri' => $this->redirectUri,<br>
);<br>
return $this->makeAccessTokenRequest($params);<br>
}<br>
public function getAccessTokenByClientCredentials($scope = '')<br>
{<br>
$params = array(<br>
'grant_type' => 'client_credentials',<br>
'client_id' => $this->clientId,<br>
'client_secret' => $this->clientSecret,<br>
'scope' => $scope,<br>
);<br>
return $this->makeAccessTokenRequest($params);<br>
}<br>
public function getAccessTokenByDeveloperCredentials($accessKey, $secretKey)<br>
{<br>
$params = array(<br>
'grant_type' => 'developer_credentials',<br>
'client_id' => $accessKey,<br>
'client_secret' => $secretKey,<br>
);<br>
return $this->makeAccessTokenRequest($params);<br>
}<br>
public function getAccessTokenByRefreshToken($refreshToken, $scope = '')<br>
{<br>
$params = array(<br>
'grant_type' => 'refresh_token',<br>
'refresh_token' => $refreshToken,<br>
'client_id' => $this->clientId,<br>
'client_secret' => $this->clientSecret,<br>
'scope' => $scope,<br>
);<br>
return $this->makeAccessTokenRequest($params);<br>
}<br>
public function makeAccessTokenRequest($params)<br>
{<br>
$result = $this->request(self::$BD_OAUTH2_ENDPOINTS['token'], $params, 'POST');<br>
if ($result) {<br>
$result = json_decode($result, true);<br>
if (isset($result['error_description'])) {<br>
$this->setError($result['error'], $result['error_description']);<br>
return false;<br>
}<br>
return $result;<br>
}<br>
<br>
return false;<br>
}<br>
<br>
public function getAccessFace($imgurl) {<br>
<br>
$retoken=$this->getAccessTokenByClientCredentials();<br>
$imgurl=urlencode($imgurl);<br>
$params = array(<br>
'access_token' => $retoken['access_token'],<br>
'url' => $imgurl,<br>
);<br>
<br>
return $this->makeAccessFaceRequest($params);<br>
}<br>
<br>
public function makeAccessFaceRequest($params){<br>
$result = $this->request(self::$BD_OAUTH2_ENDPOINTS['face'], $params, 'POST');<br>
if ($result) {<br>
$result = json_decode($result, true);<br>
if (isset($result['error_description'])) {<br>
$this->setError($result['error'], $result['error_description']);<br>
return false;<br>
}<br>
return $result;<br>
} <br>
return false; <br>
}<br>
<br>
<br>
public static function setError($errno, $errmsg)<br>
{<br>
self::$errno = $errno;<br>
self::$errmsg = $errmsg;<br>
self::errorLog($errmsg);<br>
}<br>
<br>
/**<br>
* Get the gloable errno.<br>
*<br>
* @return int<br>
*/<br>
public static function errno()<br>
{<br>
return self::$errno;<br>
}<br>
<br>
/**<br>
* Get the gloable error message.<br>
*<br>
* @return string<br>
*/<br>
public static function errmsg()<br>
{<br>
return self::$errmsg;<br>
}<br>
<br>
/**<br>
* Whether to set the debug mode of the Baidu OpenAPI SDK or not.<br>
*<br>
* @param bool $on true or false<br>
* @return void<br>
*/<br>
public static function setDebugMode($on = true)<br>
{<br>
self::$isDebug = $on;<br>
}<br>
<br>
/**<br>
* Whether the debug mode of the Baidu OpenAPI SDK is on or off.<br>
*<br>
* @return bool<br>
*/<br>
public static function isDebugMode()<br>
{<br>
return self::$isDebug;<br>
}<br>
/**<br>
* Request for a http/https resource<br>
*<br>
* @param string $url Url to request<br>
* @param array $params Parameters for the request<br>
* @param string $httpMethod Http method, 'GET' or 'POST'<br>
* @param bool $multi Whether it's a multipart POST request<br>
* @return string|false Returns string if success, or false if failed<br>
*/<br>
public static function request($url, $params = array(), $httpMethod = 'GET', $multi = false)<br>
{<br>
// when using bae(baidu app engine) to deploy the application,<br>
// just comment the following line<br>
$ch = curl_init();<br>
// when using bae(baidu app engine) to deploy the application,<br>
// and uncomment the following two lines<br>
//$fetch= new BaeFetchUrl();<br>
//$ch = $fetch->getHandle();<br>
<br>
$curl_opts = array(<br>
CURLOPT_CONNECTTIMEOUT => 3,<br>
CURLOPT_TIMEOUT => 5,<br>
CURLOPT_USERAGENT => 'baidu-apiclient-php-2.0',<br>
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,<br>
CURLOPT_RETURNTRANSFER => true,<br>
CURLOPT_HEADER => false,<br>
CURLOPT_FOLLOWLOCATION => false,<br>
);<br>
<br>
if (stripos($url, 'https://') === 0) {<br>
$curl_opts[CURLOPT_SSL_VERIFYPEER] = false;<br>
}<br>
<br>
if (strtoupper($httpMethod) === 'GET') {<br>
$query = http_build_query($params, '', '&');<br>
$delimiter = strpos($url, '?') === false ? '?' : '&';<br>
$curl_opts[CURLOPT_URL] = $url . $delimiter . $query;<br>
$curl_opts[CURLOPT_POST] = false;<br>
} else {<br>
$headers = array();<br>
if ($multi && is_array($params) && !empty($params)) {<br>
$body = self::buildHttpMultipartBody($params);<br>
$headers[] = 'Content-Type: multipart/form-data; boundary=' . self::$boundary;<br>
} else {<br>
$body = http_build_query($params, '', '&');<br>
}<br>
$curl_opts[CURLOPT_URL] = $url;<br>
$curl_opts[CURLOPT_POSTFIELDS] = $body;<br>
$curl_opts[CURLOPT_HTTPHEADER] = $headers;<br>
}<br>
<br>
curl_setopt_array($ch, $curl_opts);<br>
$result = curl_exec($ch);<br>
<br>
if ($result === false) {<br>
self::setError(curl_errno($ch), curl_error($ch));<br>
curl_close($ch);<br>
return false;<br>
} elseif (empty($result)) {<br>
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);<br>
if ($http_code != 200) {<br>
self::setError($http_code, 'http response status code: ' . $http_code);<br>
curl_close($ch);<br>
return false;<br>
}<br>
}<br>
<br>
curl_close($ch);<br>
<br>
return $result;<br>
}<br>
<br>
/**<br>
* Prints to the error log if you aren't in command line mode.<br>
*<br>
* @param String log message<br>
*/<br>
public static function errorLog($msg)<br>
{<br>
// disable error log if we are running in a CLI environment<br>
if (php_sapi_name() != 'cli') {<br>
error_log($msg);<br>
}<br>
<br>
// Set the debug mode if you want to see the errors on the page<br>
if (self::$isDebug) {<br>
echo 'error_log: '.$msg."\n";<br>
}<br>
}<br>
<br>
/**<br>
* Generate the signature for passed parameters.<br>
*<br>
* @param array $params Array of parameters to be signatured<br>
* @param string $secret Secret key for signature<br>
* @param string $namespace The parameter which will be excluded when calculate the signature<br>
* @return string Signature of the parameters<br>
*/<br>
public static function generateSign($params, $secret, $namespace = 'sign')<br>
{<br>
$str = '';<br>
ksort($params);<br>
foreach ($params as $k => $v) {<br>
if ($k != $namespace) {<br>
$str .= "$k=$v";<br>
}<br>
}<br>
$str .= $secret;<br>
return md5($str);<br>
}<br>
<br>
/**<br>
* Get the url of current page.<br>
*<br>
* @return string<br>
*/<br>
public static function getCurrentUrl()<br>
{<br>
$protocol = 'http://';<br>
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {<br>
$protocol = strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) . '://';<br>
} elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {<br>
$protocol = 'https://';<br>
}<br>
<br>
if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {<br>
$host = $_SERVER['HTTP_X_FORWARDED_HOST'];<br>
} else {<br>
$host = $_SERVER['HTTP_HOST'];<br>
}<br>
<br>
$currentUrl = $protocol . $host . $_SERVER['REQUEST_URI'];<br>
$parts = parse_url($currentUrl);<br>
<br>
$query = '';<br>
if (!empty($parts['query'])) {<br>
// drop known oauth params<br>
$params = explode('&', $parts['query']);<br>
$retained_params = array();<br>
foreach ($params as $param) {<br>
if (self::shouldRetainParam($param)) {<br>
$retained_params[] = $param;<br>
}<br>
}<br>
<br>
if (!empty($retained_params)) {<br>
$query = '?' . implode($retained_params, '&');<br>
}<br>
}<br>
<br>
// use port if non default<br>
$port = isset($parts['port']) && (($protocol === 'http://' && $parts['port'] !== 80) ||<br>
($protocol === 'https://' && $parts['port'] !== 443)) ? ':' . $parts['port'] : '';<br>
<br>
// rebuild<br>
return $protocol . $parts['host'] . $port . $parts['path'] . $query;<br>
}<br>
<br>
private static function shouldRetainParam($param)<br>
{<br>
foreach (self::$DROP_QUERY_PARAMS as $drop_query_param) {<br>
if (strpos($param, $drop_query_param . '=') === 0) {<br>
return false;<br>
}<br>
}<br>
<br>
return true;<br>
}<br>
<br>
/**<br>
* Build the multipart body for file uploaded request.<br>
* @param array $params Parameters for the request<br>
* @return string<br>
*/<br>
private static function buildHttpMultipartBody($params)<br>
{<br>
$body = '';<br>
$pairs = array();<br>
self::$boundary = $boundary = md5('BAIDU-PHP-SDK-V2' . microtime(true));<br>
<br>
foreach ($params as $key => $value) {<br>
if ($value{0} == '@') {<br>
$url = ltrim($value, '@');<br>
$content = file_get_contents($url);<br>
$array = explode('?', basename($url));<br>
$filename = $array[0];<br>
<br>
$body .= '--' . $boundary . "\r\n";<br>
$body .= 'Content-Disposition: form-data; name="' . $key . '"; filename="' . $filename . '"'. "\r\n";<br>
$body .= 'Content-Type: ' . self::detectMimeType($url) . "\r\n\r\n";<br>
$body .= $content . "\r\n";<br>
} else {<br>
$body .= '--' . $boundary . "\r\n";<br>
$body .= 'Content-Disposition: form-data; name="' . $key . "\"\r\n\r\n";<br>
$body .= $value . "\r\n";<br>
}<br>
}<br>
<br>
$body .= '--' . $boundary . '--';<br>
return $body;<br>
}<br>
<br>
/**<br>
* Tries to detect MIME type of a file<br>
*<br>
* The method will try to use fileinfo extension if it is available,<br>
* deprecated mime_content_type() function in the other case. If neither<br>
* works, default 'application/octet-stream' MIME type is returned<br>
*<br>
* @param string filename<br>
* @return string file MIME type<br>
*/<br>
private static function detectMimeType($filename)<br>
{<br>
// finfo extension from PECL available<br>
if (function_exists('finfo_open')) {<br>
if (!isset(self::$fileinfoDb)) {<br>
self::$fileinfoDb = finfo_open(FILEINFO_MIME);<br>
}<br>
if (self::$fileinfoDb) {<br>
$info = finfo_file(self::$fileinfoDb, $filename);<br>
}<br>
}<br>
// (deprecated) mime_content_type function available<br>
if (empty($info) && function_exists('mime_content_type')) {<br>
$info = mime_content_type($filename);<br>
}<br>
return empty($info)? 'application/octet-stream': $info;<br>
}<br>
}
第四步,在Common目录添加方法代码如下function face($url){<br>
$clientId = '这里用API Key替换';<br>
$clientSecret = '这里用Secret Key替换';<br>
$image = new \Org\Util\Baidu($clientId,$clientSecret);<br>
return $image->getAccessFace($url);<br>
}
第五步,使用函数
$url='http://xxx.xxx.com/xxx/xxx.jpg';
dump(face($url));
成功返回:
array(6) {
["face"] => array(1) {
[0] => array(3) {
["face_id"] => string(32) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
["attribute"] => array(3) {
["gender"] => array(2) {
["confidence"] => string(8) "1.000000"
["value"] => string(6) "female"
}
["smiling"] => array(1) {
["confidence"] => string(8) "0.131746"
}
["face"] => array(2) {
["value"] => string(4) "true"
["confidence"] => string(4) "0.19"
}
}
["position"] => array(6) {
["center"] => array(2) {
["x"] => string(8) "0.653580"
["y"] => string(8) "0.285610"
}
["width"] => string(8) "0.624930"
["height"] => string(8) "0.468110"
["eye_left"] => array(2) {
["x"] => string(8) "0.541770"
["y"] => string(8) "0.115710"
}
["eye_right"] => array(2) {
["x"] => string(8) "0.875140"
["y"] => string(8) "0.186870"
}
["mouth"] => array(2) {
["x"] => string(8) "0.640980"
["y"] => string(8) "0.440060"
}
}
}
}
["img_id"] => string(32) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
["url"] => string(35) "http://xxx.xxx.com/xxx/xxx.jpg"
["session_id"] => string(32) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
["img_width"] => string(3) "200"
["img_height"] => string(3) "267"
AD:真正免费,域名+虚机+企业邮箱=0元

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Learn about Python programming with introductory code examples Python is an easy-to-learn, yet powerful programming language. For beginners, it is very important to understand the introductory code examples of Python programming. This article will provide you with some concrete code examples to help you get started quickly. Print HelloWorldprint("HelloWorld") This is the simplest code example in Python. The print() function is used to output the specified content

PHP variables store values during program runtime and are crucial for building dynamic and interactive WEB applications. This article takes an in-depth look at PHP variables and shows them in action with 10 real-life examples. 1. Store user input $username=$_POST["username"];$passWord=$_POST["password"]; This example extracts the username and password from the form submission and stores them in variables for further processing. 2. Set the configuration value $database_host="localhost";$database_username="username";$database_pa

Title: From Beginner to Mastery: Code Implementation of Commonly Used Data Structures in Go Language Data structures play a vital role in programming and are the basis of programming. In the Go language, there are many commonly used data structures, and mastering the implementation of these data structures is crucial to becoming a good programmer. This article will introduce the commonly used data structures in the Go language and give corresponding code examples to help readers from getting started to becoming proficient in these data structures. 1. Array Array is a basic data structure, a group of the same type

The simplest code example of Java bubble sort Bubble sort is a common sorting algorithm. Its basic idea is to gradually adjust the sequence to be sorted into an ordered sequence through the comparison and exchange of adjacent elements. Here is a simple Java code example that demonstrates how to implement bubble sort: publicclassBubbleSort{publicstaticvoidbubbleSort(int[]arr){int

"Go Language Programming Examples: Code Examples in Web Development" With the rapid development of the Internet, Web development has become an indispensable part of various industries. As a programming language with powerful functions and superior performance, Go language is increasingly favored by developers in web development. This article will introduce how to use Go language for Web development through specific code examples, so that readers can better understand and use Go language to build their own Web applications. 1. Simple HTTP Server First, let’s start with a

How to use PHP to write the inventory management function code in the inventory management system. Inventory management is an indispensable part of many enterprises. For companies with multiple warehouses, the inventory management function is particularly important. By properly managing and tracking inventory, companies can allocate inventory between different warehouses, optimize operating costs, and improve collaboration efficiency. This article will introduce how to use PHP to write code for inventory warehouse management functions, and provide you with relevant code examples. 1. Establish the database before starting to write the code for the inventory warehouse management function.

Java Selection Sorting Method Code Writing Guide and Examples Selection sorting is a simple and intuitive sorting algorithm. The idea is to select the smallest (or largest) element from the unsorted elements each time and exchange it until all elements are sorted. This article will provide a code writing guide for selection sorting, and attach specific Java sample code. Algorithm Principle The basic principle of selection sort is to divide the array to be sorted into two parts, sorted and unsorted. Each time, the smallest (or largest) element is selected from the unsorted part and placed at the end of the sorted part. Repeat the above

Huawei Cloud Edge Computing Interconnection Guide: Java Code Samples to Quickly Implement Interfaces With the rapid development of IoT technology and the rise of edge computing, more and more enterprises are beginning to pay attention to the application of edge computing. Huawei Cloud provides edge computing services, providing enterprises with highly reliable computing resources and a convenient development environment, making edge computing applications easier to implement. This article will introduce how to quickly implement the Huawei Cloud edge computing interface through Java code. First, we need to prepare the development environment. Make sure you have the Java Development Kit installed (
