使用 curl 发起 POST 请求,携带 access_token 和 Base64 编码的图片数据调用百度 AI OCR API。

获取 access_token 与准备图片
调用接口前需先通过 App ID 和 Secret Key 获取 access_token,并将本地图片文件读取为 Base64 字符串。这是所有后续操作的基础前提。

access_token 的有效期通常为 30 天,建议在生产环境中缓存该值以避免频繁请求。图片预处理时,确保图片格式为 JPG、PNG 等常见格式,且大小不超过 API 限制(通常 4MB)。Base64 编码时需去除前缀如 data:image/jpeg;base64,,仅保留纯编码部分。
构造请求并解析 JSON 响应
将 Token 和图片数据组装到 HTTP 请求体中,发送请求后解析返回的 JSON 数据提取文字结果。

<?php
// 配置信息
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$imagePath = 'test.jpg';
// 1. 获取 access_token
function getAccessToken($apiKey, $secretKey) {
$url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={$apiKey}&client_secret={$secretKey}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
return $data['access_token'] ?? '';
}
// 2. 读取图片并转 Base64
function getImageBase64($path) {
if (!file_exists($path)) {
throw new Exception("Image file not found: {$path}");
}
$imageData = file_get_contents($path);
return base64_encode($imageData);
}
// 3. 调用 OCR API
function ocrGeneral($accessToken, $base64Image) {
$url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token={$accessToken}";
$postFields = [
'image' => $base64Image,
'language_type' => 'CHN_ENG', // 中英文混合
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
// 执行流程
try {
$token = getAccessToken($apiKey, $secretKey);
if (empty($token)) {
die('Failed to get access token');
}
$imgBase64 = getImageBase64($imagePath);
$result = ocrGeneral($token, $imgBase64);
if (isset($result['error_code'])) {
echo "Error: " . $result['error_msg'];
} else {
foreach ($result['words_result'] as $word) {
echo $word['words'] . PHP_EOL;
}
}
} catch (Exception $e) {
echo $e->getMessage();
}
程序输出识别出的每一行文字,每行独立打印。若图片路径错误或 Token 失效,将抛出异常或打印错误信息。修改 language_type 可适配日文、韩文等场景,但需注意 API 版本支持情况。
请求头需设置 Content-Type: application/x-www-form-urlencoded。API 返回的数据结构包含 words_result 数组,每个元素代表一行或一个识别块的文字内容。若返回 error_code 非 0,则说明请求失败,需根据错误码排查参数或权限问题。
处理多行文本与坐标信息
OCR 返回的结果通常包含每行文字的坐标点,可用于还原排版或过滤噪声。
实际开发中,开发者常忽略 words_result 中的 location 字段。该字段提供左上角和右下角坐标,可用于判断文字方向或进行简单的版面分析。对于垂直排列的文字,可能需要对坐标进行排序重组。置信度 confidence 较低的结果可视为噪声予以剔除。