最近一个程序用到了腾旭的人脸融合接口,类似于天天p图的功能
接口参考文档https://ai.qq.com/doc/facemerge.shtml
下面是一个demo
<?php
error_reporting(0);
/**
* Class Common
* by sdxjwkq
*/
class Common{
protected function getReqSign($params /* 关联数组 */, $appkey /* 字符串*/)
{
// 1. 字典升序排序
ksort($params);
// 2. 拼按URL键值对
$str = '';
foreach ($params as $key => $value)
{
if ($value !== '')
{
$str .= $key . '=' . urlencode($value) . '&';
}
}
// 3. 拼接app_key
$str .= 'app_key=' . $appkey;
// 4. MD5运算+转换大写,得到请求签名
$sign = strtoupper(md5($str));
return $sign;
}
protected function doHttpPost($url, $params)
{
$curl = curl_init();
$response = false;
do
{
// 1. 设置HTTP URL (API地址)
curl_setopt($curl, CURLOPT_URL, $url);
// 2. 设置HTTP HEADER (表单POST)
$head = array(
'Content-Type: application/x-www-form-urlencoded'
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $head);
// 3. 设置HTTP BODY (URL键值对)
$body = http_build_query($params);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
// 4. 调用API,获取响应结果
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_NOBODY, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
if ($response === false)
{
$response = false;
break;
}
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($code != 200)
{
$response = false;
break;
}
} while (0);
curl_close($curl);
return $response;
}
}
class facemerge extends Common{
private $path="./z.jpg";//图片文件路径
public function index() {
$path =
$data = file_get_contents($this->path);
$base64 = base64_encode($data);
// 设置请求数据
$appkey = 'vLHhvee687gUW6Cr';
$params = array(
'app_id' => 'xxxxxx',
'image' => $base64,
'model' => '32',
'time_stamp' => strval(time()),
'nonce_str' => strval(rand()),
'sign' => '',
);
$params['sign'] = $this->getReqSign($params, $appkey);
// edump($params);
// 执行API调用
$url = 'https://api.ai.qq.com/fcgi-bin/ptu/ptu_facemerge';
$response = $this->doHttpPost($url, $params);
$img = json_decode($response,true);
if($img['ret']!='4096'){
$img = "<img src='data:image/jpg;base64,".$img['data']['image']."'/>'";
// $img = base64_decode($img);
echo $img;
}else{
echo 1;
}
}
}
$faceFusion=new facemerge();
$faceFusion->index();
效果如下
api提供了多个模板选择,也可以自定义