Before integrating Baidu's Handwriting Recognition API with PHP, it's important to understand the basics. The Handwriting Recognition API offered by Baidu converts handwritten text into digital text and supports the recognition of Chinese, English, numbers, and symbols.
This API is provided by the Baidu AI Open Platform. For more details, refer to the official documentation to learn how to obtain an API Key and start using it. With this API, you can convert handwritten content into editable text.
Before using the Baidu Handwriting Recognition API, please note the following requirements:
Detailed usage, request examples, return parameter explanations, and error code descriptions are available in the official Baidu AI Open Platform documentation. You can find examples of API requests, error code explanations, and other important information there.
Next, we will start integrating Baidu Handwriting Recognition API with PHP. Below are the specific steps:
First, log in to the Baidu AI Open Platform and create an application to obtain your API Key and Secret Key. These values will be required for subsequent API requests.
Before sending the API request, you need to generate a signature for the request parameters. You can refer to Baidu AI Platform documentation for this process. Here’s an example of how to generate the signature:
function getSign($requestParams, $secretKey) {
ksort($requestParams);
reset($requestParams);
$str = "";
foreach ($requestParams as $key => $value) {
$str .= $key . "=" . urlencode($value) . "&";
}
$str .= "app_key=" . APP_KEY;
return strtoupper(md5($str . $secretKey));
}
Once the signature is generated, the next step is to send the API request. Below is an example of PHP code for sending the POST request:
$url = "https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting";
$requestParams = array(
"access_token" => ACCESS_TOKEN,
"image" => base64_encode(file_get_contents("handwriting.jpg")),
"probability" => "true",
"recognize_granularity" => "big"
);
$requestParams["sign"] = getSign($requestParams, SECRET_KEY);
$response = file_get_contents($url . "?" . http_build_query($requestParams));
print_r($response);
The API response includes the recognized text and confidence levels. You can use PHP to parse the response and extract the recognized text. Below is an example code for handling the API response:
$responseArr = json_decode($response, true);
if (isset($responseArr["words_result"])) {
foreach ($responseArr["words_result"] as $word) {
echo $word["words"];
}
} else {
echo "No text recognized";
}
This article introduced how to integrate Baidu's Handwriting Recognition API with PHP, covering the API requirements, obtaining API keys, signature generation, sending requests, and parsing responses. By following these steps, developers can quickly implement handwriting recognition features.