本帖最后由 宝宝丷 于 2023-4-4 19:39 编辑
[PHP] 纯文本查看 复制代码 // 配置 APP_ID, API_KEY, SECRET_KEY
$app_id = 'YOUR_APP_ID';
$api_key = 'YOUR_API_KEY';
$secret_key = 'YOUR_SECRET_KEY';
// 印章图片路径
$image_path = 'YOUR_IMAGE_PATH';
// 调用百度OCR API 进行印章识别
$url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/seal';
$access_token = get_access_token($app_id, $api_key, $secret_key);
$img_base64 = base64_encode(file_get_contents($image_path));
$data = array(
'image' => $img_base64,
'detect_direction' => 'true',
'probability' => 'true'
);
$result = request_post($url, $data, $access_token);
// 输出结果
print_r($result);
// 获取百度 OCR API 的 access_token
function get_access_token($app_id, $api_key, $secret_key) {
$url = 'https://aip.baidubce.com/oauth/2.0/token';
$post_data['grant_type'] = 'client_credentials';
$post_data['client_id'] = $api_key;
$post_data['client_secret'] = $secret_key;
$o = "";
foreach ($post_data as $k=>$v)
{
$o.= "$k=" . urlencode( $v ). "&" ;
}
$post_data = substr($o,0,-1);
$res = request_post($url, $post_data);
$access_token = json_decode($res, true)['access_token'];
return $access_token;
}
// 发送 POST 请求
function request_post($url = '', $post_data = array(), $access_token = '') {
if(false == $url || empty($post_data)){
return false;
}
if(!empty($access_token)){
$url = $url.'?access_token='.$access_token;
}
$o = "";
foreach ($post_data as $k=>$v)
{
$o.= "$k=" . urlencode( $v ). "&" ;
}
$post_data = substr($o,0,-1);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
以上代码中,$app_id、$api_key、$secret_key 分别为百度 OCR API 的 APP_ID、API_KEY 和 SECRET_KEY,需要替换成自己的信息;$image_path 为要识别的印章图片路径,也需要替换成自己的路径。运行代码后,会输出印章识别结果。 |