当前位置:
首页
文章
前端
详情

PHP使用微软认知服务Face API

实验环境:

  • IDE:Eclipse for PHP Developers
  • Version: Neon.1 Release (4.6.1)
  • Server:WampServer Version 2.5
  • HttpClient:guzzle

1. 使用composer安装Guzzle

  • composer.json文件

    { "require": { "guzzlehttp/guzzle": "~6.0" } }

  • composer.phar下载

  • 打开控制台指令,在项目目录下运行如下指令完成包的安装

    php composer.phar install

2. 证书安装

注意:默认的http客户端工具一般到需要证书的认证,如果没有导入相应的证书一般会报SSL证书认证错误。

  • 下载证书到本地,下载地址,将其保存到相应的位置。

  • 为了让证书生效需要相应修改php.ini,修改方法如下:

    curl.cainfo =/cacert.pem

3. PHP代码示例

<?php
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Client;

require_once 'vendor\autoload.php';

$client = new Client();

$headers = ['Content-Type' => 'application/json','Ocp-Apim-Subscription-Key' => '{key}'];
$body = '{"url":"{image's url}"}';

$request = new Request('POST','https://api.cognitive.azure.cn/face/v1.0/detect', $headers , $body);

$response = $client->send($request);

echo $response->getBody();
?>

4. 运行结果示例

[{"faceId":"b22efa8f-0e34-4344-8346-ca8b79d29a27","faceRectangle":{"top":181,"left":184,"width":257,"height":257}}]

5. 读取本地图片

<?php

use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Client;

require_once 'vendor\autoload.php';

$client = new Client();

$headers = ['Content-Type' => 'application/octet-stream','Ocp-Apim-Subscription-Key' => 'bd8e4ce12f444c639ac9c214d70ac72c'];

$myfile = fopen("tt.jpg", "r") or die("Unable to open file!");

$request = new Request('POST','https://api.cognitive.azure.cn/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age', $headers , $myfile);

$response = $client->send($request);

echo $response->getBody();

fclose($myfile);
?>

6. 更多参考

  • 关于key的获取可以登录世纪互联官方网站申请账户,在新版本的 portal 中即可创建认知服务。
  • 认知服务RestAPI参考

免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。