<?php
require_once 'aliyun-oss-php-sdk/autoload.php';
include_once 'aliyun-php-sdk-core/Config.php';
use Green\Request\V20180509 as Green;
use Green\Request\Extension\ClientUploader;
class Index{
private $config = [
'accessKeyId' => ''
,'accessSecret' => ''
]; // 自己配置
private $client;
public function __construct()
{
$iClientProfile = DefaultProfile::getProfile("cn-shanghai", $this->config['accessKeyId'], $this->config['accessSecret']);
DefaultProfile::addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
$this->client = new DefaultAcsClient($iClientProfile);
}
public function index($path)
{
$request = new Green\ImageSyncScanRequest();
$request->setMethod("POST");
$request->setAcceptFormat("JSON");
// 先上传本地文件再进行检测。
$uploader = ClientUploader::getImageClientUploader($this->client);
$url = $uploader->uploadFile($path);
$task1 = array('dataId' => uniqid(),
'url' => $url,
);
// 设置待检测的图片,一张图片对应一个检测任务。
// 多张图片同时检测时,处理时间由最后一张处理完的图片决定。
// 通常情况下批量检测的平均响应时间比单张检测要长。一次批量提交的图片数越多,响应时间被拉长的概率越高。
// 代码中以单张图片检测作为示例,如果需要批量检测多张图片,请自行构建多个检测任务。
// 一次请求中可以同时检测多张图片,每张图片可以同时检测多个风险场景,计费按照单图片单场景检测叠加计算。
// 例如,检测2张图片,场景传递porn和terrorism,则计费按照2张图片鉴黄和2张图片暴恐检测计算。
$request->setContent(json_encode(array("tasks" => array($task1),
"scenes" => array("porn"))));
$response = $this->client->getAcsResponse($request);
$arr = [];
try {
$response = $this->client->getAcsResponse($request);
if(200 == $response->code){
$taskResults = $response->data;
foreach ($taskResults as $taskResult) {
if(200 == $taskResult->code){
$sceneResults = $taskResult->results;
foreach ($sceneResults as $sceneResult) {
$scene = $sceneResult->scene;
$suggestion = $sceneResult->suggestion;
// 根据scene和suggetion设置后续操作。
// 根据不同的suggestion结果做业务上的不同处理。例如,将违规数据删除等。
$arr = ['scene'=>$scene,'suggestion'=>$suggestion];
}
}else{
print_r("任务过程失败:" + $response->code);
}
}
}else{
print_r("检测不成功。代码:" + $response->code);
}
} catch (Exception $e) {
print_r($e);
}
return $arr;
}
}
- 然后在其他控制器调用
public function img()
{
$file = $this->request->file('file');
$path = $file->getPathInfo() .'/'. $file->getFilename();
import('aliyuncs.Index', EXTEND_PATH,".php");
$aliyuncs = new \Index();
$info = $aliyuncs->index($path);
$this->success("鉴定成功",$info);
}
6.返回示例
{
"code": 1,
"msg": "鉴定成功",
"time": "1609294092",
"data": {
"scene": "porn", // 鉴黄
"suggestion": "pass" // / block:涉黄 pass:正常
}
}