首先需要在百度智慧雲上註冊號
(其註冊步驟可參考CSDN部落格)
blog.csdn.net/qq_59208918/article/...
程式碼實現
將以下程式碼放置控制器即可,或者進行封裝呼叫
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Audit
{
/**
* 內容稽核
*/
public function contentAudit(Request $request)
{
$content = $request->post('content');
//ApiKey和SecretKey從自己在百度智慧雲上建立的應用資訊裡獲取
$token = $this->getAccessToken('ApiKey ', 'SecretKey ');
$url = 'https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=' . $token;
$bodys = array(
'text' => $content
);
$res = $this->curlPost($url, $bodys);
//結果轉成陣列
$res = json_decode($res, true);
//根據自己的業務邏輯進行處理
return $res;
}
/**
* 圖片稽核
*/
public function imageAudit()
{
$fileTmp = $request->file('image')->getPathname();
$token = $this->getAccessToken('ApiKey ', 'SecretKey ');
$url = 'https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=' . $token;
$img = file_get_contents($fileTmp);//本地路徑
$img = base64_encode($img);
$bodys = array(
'image' => $img
);
$res = $this->curlPost($url, $bodys);
//結果轉成陣列
$res = json_decode($res, true);
//根據自己的業務邏輯進行處理
return $res;
}
/**
* CURL的Post請求方法
* @param string $url
* @param string $param
* @return bool|string
*/
function curlPost($url = '', $param = '')
{
if (empty($url) || empty($param)) {
return false;
}
$postUrl = $url;
$curlPost = $param;
// 初始化curl
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $postUrl);
curl_setopt($curl, CURLOPT_HEADER, 0);
// 要求結果為字串且輸出到螢幕上
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
// post提交方式
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
// 執行curl
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
/**
* 獲取百度開放平臺的票據
* 參考連結:https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
*/
public function getAccessToken($ApiKey = '', $SecretKey = '', $grantType = 'client_credentials')
{
$url = 'https://aip.baidubce.com/oauth/2.0/token';
$post_data['grant_type'] = $grantType;
$post_data['client_id'] = $ApiKey;
$post_data['client_secret'] = $SecretKey;
$o = "";
foreach ($post_data as $k => $v) {
$o .= "$k=" . urlencode($v) . "&";
}
$post_data = substr($o, 0, -1);
$res = $this->curlPost($url, $post_data);
//進行把返回結果轉成陣列
$res = json_decode($res, true);
if (isset($res['error'])) {
exit('API Key或者Secret Key不正確');
}
$accessToken = $res['access_token'];
return $accessToken;
}
}
以下為效果圖,可供參考
本作品採用《CC 協議》,轉載必須註明作者和本文連結