代码 php阿里云图片检测单代码不用sdk太重了

2024-11-19 03:16:06 +0800 CST views 555

该代码实现了一个阿里云图片内容安全审核的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);
}

复制全文 生成海报 编程 云计算 安全 API PHP

推荐文章

软件定制开发流程
2024-11-19 05:52:28 +0800 CST
Vue3中如何处理组件间的动画?
2024-11-17 04:54:49 +0800 CST
如何在Vue 3中使用Ref访问DOM元素
2024-11-17 04:22:38 +0800 CST
批量导入scv数据库
2024-11-17 05:07:51 +0800 CST
一个收银台的HTML
2025-01-17 16:15:32 +0800 CST
Elasticsearch 聚合和分析
2024-11-19 06:44:08 +0800 CST
js函数常见的写法以及调用方法
2024-11-19 08:55:17 +0800 CST
Rust 高性能 XML 读写库
2024-11-19 07:50:32 +0800 CST
15 个 JavaScript 性能优化技巧
2024-11-19 07:52:10 +0800 CST
如何开发易支付插件功能
2024-11-19 08:36:25 +0800 CST
前端项目中图片的使用规范
2024-11-19 09:30:04 +0800 CST
Python上下文管理器:with语句
2024-11-19 06:25:31 +0800 CST
php客服服务管理系统
2024-11-19 06:48:35 +0800 CST
基于Webman + Vue3中后台框架SaiAdmin
2024-11-19 09:47:53 +0800 CST
php常用的正则表达式
2024-11-19 03:48:35 +0800 CST
介绍 Vue 3 中的新的 `emits` 选项
2024-11-17 04:45:50 +0800 CST
微信小程序热更新
2024-11-18 15:08:49 +0800 CST
程序员茄子在线接单