该代码实现了一个阿里云图片内容安全审核的PHP类,包含构造函数、调用接口的scanImage方法、解析错误响应的parseAliyunErrorResponse方法和生成签名的generateSignature方法。通过cURL请求阿里云的接口,检测指定URL的图片是否包含不当内容,并返回结果。
php阿里云图片检测单代码不用sdk太重了
<?php
class AliyunImageAudit
{
private $accessKeyId;
private $accessKeySecret;
private $endpoint = "https://imageaudit.cn-shanghai.aliyuncs.com";
public function __construct($accessKeyId, $accessKeySecret)
{
$this->accessKeyId = $accessKeyId;
$this->accessKeySecret = $accessKeySecret;
}
/**
* 调用阿里云图片内容安全接口
* @param string $imageUrl 待检测图片的URL
* @param array $scenes 需要检测的场景数组,例如 ['porn', 'terrorism']
* @return array|string 接口返回的JSON数据
*/
public function scanImage($imageUrl, $scenes = ['porn'])
{
$path = "/";
$action = "ScanImage";
$version = "2019-12-30";
$timestamp = gmdate("Y-m-d\TH:i:s\Z");
$nonce = uniqid();
// URL参数(按字母顺序排序)
$params = [
"Action" => $action,
"Version" => $version,
"AccessKeyId" => $this->accessKeyId,
"Timestamp" => $timestamp,
"SignatureNonce" => $nonce,
"SignatureMethod" => "HMAC-SHA1",
"SignatureVersion" => "1.0",
"Scene" => json_encode($scenes),
"Task" => json_encode([["ImageURL" => $imageUrl, "DataId" => uniqid()]]),
];
// 生成签名
$signature = $this->generateSignature($params);
// 将签名添加到参数中
$params["Signature"] = $signature;
// 构造URL查询字符串
$queryParams = http_build_query($params);
// 请求头
$headers = [
"Content-Type: application/json"
];
// 使用cURL发起请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->endpoint . $path . '?' . $queryParams);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$response = curl_exec($ch);
$response = $this->parseAliyunErrorResponse( $response);
if (curl_errno($ch)) {
return "Error: " . curl_error($ch);
}
curl_close($ch);
return $response;
}
/**
* 将XML格式的错误响应解析为数组
* @param string $xmlResponse XML格式的错误响应
* @return array 解析后的数组
*/
function parseAliyunErrorResponse($xmlResponse)
{
// 解析XML为SimpleXMLElement对象
$xmlObject = simplexml_load_string($xmlResponse, "SimpleXMLElement", LIBXML_NOCDATA);
// 将SimpleXMLElement对象转换为JSON,然后解码为数组
$json = json_encode($xmlObject);
$responseArray = json_decode($json, true);
return $responseArray;
}
/**
* 生成签名
* @param array $params 请求参数数组
* @return string 生成的签名
*/
private function generateSignature($params)
{
// 参数按字母顺序排序并URL编码
ksort($params);
$canonicalizedQueryString = '';
foreach ($params as $key => $value) {
$canonicalizedQueryString .= '&' . rawurlencode($key) . '=' . rawurlencode($value);
}
$canonicalizedQueryString = ltrim($canonicalizedQueryString, '&');
// 构造待签名字符串
$stringToSign = "POST&%2F&" . rawurlencode($canonicalizedQueryString);
// 计算签名
return base64_encode(hash_hmac("sha1", $stringToSign, $this->accessKeySecret . "&", true));
}
}
echo "<pre>";
// 使用示例
$accessKeyId = "LTAI5tNBbf1VobtmiPDVv2bR";
$accessKeySecret = "";
$imageAudit = new AliyunImageAudit($accessKeyId, $accessKeySecret);
$imageUrl = "http://mh.ipif.cn/static/index/img/1.png";
$result = $imageAudit->scanImage($imageUrl, ['porn', 'terrorism']);
print_r($result); // 输出检测结果
<?php
namespace app\service;
use AlibabaCloud\SDK\Imageaudit\V20191230\Imageaudit;
use AlibabaCloud\SDK\Imageaudit\V20191230\Models\ScanImageAdvanceRequest;
use AlibabaCloud\SDK\Imageaudit\V20191230\Models\ScanImageAdvanceRequest\task;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use GuzzleHttp\Psr7\Stream;
use think\Db;
use think\Exception;
class ImageAuditService
{
private $accessKeyId = "LTAI5"; // 替换为你的 Access Key ID
private $accessKeySecret = "YWLY92f4x4A6ux4BjJL5qIi6vdTWN3"; // 替换为你的 Access Key Secret
// 创建客户端
private function createClient()
{
$config = new Config([
"accessKeyId" => $this->accessKeyId,
"accessKeySecret" => $this->accessKeySecret
]);
$config->endpoint = "imageaudit.cn-shanghai.aliyuncs.com";
return new Imageaudit($config);
}
// 图片审核方法
public function auditImage($imageUrl)
{
// 计算图片的 MD5 值,用于去重判断
$picmd5 = md5_file($imageUrl);
// 检查数据库中是否已存在此图片的审核记录
$existingRecord = Db::name('image_audit')->where('picmd5', $picmd5)->find();
if ($existingRecord) {
return $existingRecord['is_passed'] ? true : $existingRecord['data'];
}
// 初始化客户端
$client = $this->createClient();
// 准备请求参数
$file = fopen($imageUrl, 'rb');
$stream = new Stream($file);
$task = new task(["imageURLObject" => $stream]);
$scanImageAdvanceRequest = new ScanImageAdvanceRequest([
"task" => [$task],
"scene" => ["terrorism", "porn"]
]);
$runtime = new RuntimeOptions([]);
try {
// 发起请求
$response = $client->scanImageAdvance($scanImageAdvanceRequest, $runtime);
$responseData = json_decode(Utils::toJSONString($response->body), true);
// 处理结果
$results = $responseData['Data']['Results'][0]['SubResults'] ?? [];
$isPassed = true;
foreach ($results as $result) {
if (in_array($result['Scene'], ['porn', 'terrorism']) &&
$result['Label'] == 'normal' &&
$result['Rate'] > 80) {
continue;
} else {
$isPassed = false;
break;
}
}
// 存储数据到数据库
Db::name('image_audit')->insert([
'pic' => $imageUrl,
'picmd5' => $picmd5,
'data' => json_encode($responseData),
'created_at' => date('Y-m-d H:i:s'),
'is_passed' => $isPassed ? 1 : 0
]);
return $isPassed ? true : $responseData;
} catch (Exception $exception) {
// 捕获异常并返回
return [
'error' => true,
'message' => $exception->getMessage(),
'code' => $exception->getCode()
];
}
}
}
// 引入服务类
use app\service\ImageAuditService;
// 初始化服务
$auditService = new ImageAuditService();
// 调用图片审核方法,传入图片URL
$result = $auditService->auditImage('https://example.com/image.jpg');
// 检查结果
if ($result === true) {
echo "图片审核通过";
} else {
echo "图片审核未通过,返回信息:" . json_encode($result);
}