• 周五. 4月 26th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

tp5上传阿里云oss并对接阿里云检测人脸(DetectFace)

admin

11月 28, 2021

需求:上传照片之后,需要检测上传的照片里是否存在人脸,如果不存在则不能通过。

流程需要分两步:第一步,先上传至阿里云的oss,获得照片的url,第二步,再使用第一步获得的url去检测(PS:阿里云的人脸检测只能支持oss地址,而且必须是上海地区的Bucket)。

请先获取阿里云的OSS和人脸的appid和key等配置信息。

获取到之后,再将配置信息新增到【config.php】文件里:

新增内容:

    //阿里云配置
    'aliyun'        =>[
        'AccessKeyID'      => 'LTA******ZzQ',
        'AccessKeySecret'  => 'uzY9*******QrFc',
        'EndPoint'   => 'oss-cn-shanghai.aliyuncs.com',
        'Bucket'     => 'ai****ace',
        'face'      => [
            'AccessKeyID'      => 'LT******ZzQ',
            'AccessKeySecret'  => 'uz*******QrFc',
            'endpoint'   => 'facebody.cn-shanghai.aliyuncs.com',
        ],
    ],

先讲一下上传OSS(PS:已经懂得怎么上传的,请略过第一步)点此跳转至第二步

点此下载 oss sdk(地址:https://github.com/aliyun/aliyun-oss-php-sdk)

下载后,解压到项目的【extend】文件夹

解压完成后,在公共的地方新建一个文件【AliOssUpload】。在哪新建都行,只要后面能调用到就行。本人新建在 common/controller下

【AliOssUpload】文件内容:

<?php
namespace appcommoncontroller;

use thinkController;

require_once APP_PATH . '/../extend/aliyun-oss/autoload.php'; //引入阿里云OSS SDK,注意替换路径
use OSSCoreOssException;
use OSSOssClient;

class AliOssUpload
{

    /**
     * 调用阿里云OSS SDK
     * @param string $fileName 上传的文件
     * @param string $path 上传的文件
     * @return array 阿里云OSS上传处理结果
     *
     */
    public static function AliuploadFile($fileName, $path)
    {
        try {
            //获取OSS参数值
            $KeyId = config('aliyun.AccessKeyID');
            $KeySecret = config('aliyun.AccessKeySecret');
            $EndPoint = config('aliyun.EndPoint');
            $Bucket = config('aliyun.Bucket');
            //实例化
            $ossClient = new OssClient($KeyId, $KeySecret, $EndPoint);
            //执行阿里云上传
            $result = $ossClient->uploadFile($Bucket, $fileName, $path);
            //图片地址:$result['info']['url']
            $arr = ['code' => 200, 'msg' => '上传成功', 'data' => $result['info']['url']];
        } catch (OssException $e) {
            $arr = ['code' => 0, 'msg' => $e->getMessage(), 'data' => ''];
        }
        return $arr;
    }
}

然后就是调用了,在api/controller里新建【Face.php】文件:

<?php
namespace appapicontroller;  

use appcommoncontrollerApi;
use appcommoncontrollerAliOssUpload; //这里就是引用上面的文件

/**
 * 人脸接口
 */
class Face extends Api
{
    protected $noNeedLogin = ['*']; //是否需要登录 *表示全部都不
    protected $noNeedRight = '*';  //是否需要鉴权 *表示全部都不/**
     * 文件上传接口
     * @param string $file
     * @return bool
     */
    public static function uploadFile($file)
    {
//        $file = "/uploads/20210624/aa159505d9bad351634bd4b89b674e2b.png";
        $path = ROOT_PATH . "public" . $file;   //绝对路径
        $file = str_replace('/', '-', substr($file, 1)); //名字里不能出现 / 否则上传失败

        //调用阿里云OSS上传
        $res = AliOssUpload::AliuploadFile($file, $path);
        if ($res['code'] != 200) {
            return false;
        }
        return $res['data'];
    }
}

至此,上传阿里云的OSS结束。

传完后,就要拿返回的url去做人脸检测了。

可以直接使用composer装人脸的SDK:

composer require alibabacloud/facebody-20191230 1.0.11

装完之后,在api/controller的【Face.php】文件新增调用人脸方法,完整的文件内容如下:

<?php

namespace appapicontroller;

use appcommoncontrollerApi;
use appcommoncontrollerAliOssUpload;

use AlibabaCloudSDKFacebodyV20191230Facebody;
use AlibabaCloudTeaTea;
use DarabonbaOpenApiModelsConfig;
use AlibabaCloudSDKFacebodyV20191230ModelsDetectFaceRequest;

/**
 * 人脸接口
 */
class Face extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';


    protected $model = null;
    protected $relationSearch = true;


    /**
     * 文件上传接口
     * @param string $file
     * @return bool
     */
    public static function uploadFile($file)
    {
//        $file = "/uploads/20210624/aa159505d9bad351634bd4b89b674e2b.png";
        $path = ROOT_PATH . "public" . $file;   //绝对路径
        $file = str_replace('/', '-', substr($file, 1)); //名字里不能出现 / 否则上传失败

        //调用阿里云OSS上传
        $res = AliOssUpload::AliuploadFile($file, $path);
        if ($res['code'] != 200) {
            return false;
        }
//     if (isset($res['data']) && self::getFace($res['data'])) {
//       return true;
//     }
return $res['data']; } /** * 是否存在人脸 * @param string $img 阿里云OSS的图片地址 * @return bool */ public static function getFace($img) { $args = config('aliyun.face'); $args['imageURL'] = $img; return self::main($args); } /** * 使用AK&SK初始化账号Client * @param string $accessKeyId * @param string $accessKeySecret * @param string $endpoint * @return Facebody Client */ public static function createClient($accessKeyId, $accessKeySecret, $endpoint) { $config = new Config([ // 您的AccessKey ID "accessKeyId" => $accessKeyId, // 您的AccessKey Secret "accessKeySecret" => $accessKeySecret ]); // 访问的域名 $config->endpoint = $endpoint; return new Facebody($config); } /**
   * 调用阿里云人脸检测 * @param array $args * @return bool
*/ public static function main($args) { try { $client = self::createClient($args['AccessKeyID'], $args['AccessKeySecret'], $args['endpoint']); $detectFaceRequest = new DetectFaceRequest([ "imageURL" => $args['imageURL'] ]); $resp = $client->detectFace($detectFaceRequest); $faceInfo = Tea::merge($resp); if (isset($faceInfo['body']) && $faceInfo['body']['Data']['FaceCount'] >= 1) { return true; } return false; // die; // Console::log(Utils::toJSONString(Tea::merge($resp))); } catch (Exception $exception) { return false; } } }
 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注