Simple tutorial: How to connect PHP to Baidu image definition recognition interface?
Introduction:
Baidu image clarity recognition interface is a powerful image processing function provided by Baidu AI open platform. Through this interface, we can use Baidu AI's powerful algorithm to judge the clarity of an image and derive a corresponding score. This tutorial will show how to use PHP code to connect to Baidu's image clarity recognition interface.
Environment preparation:
Step 1: Obtain the Base64 encoding of the image through POST request
<?php function imgToBase64($imgPath) { $imgInfo = getimagesize($imgPath); $fp = fopen($imgPath, 'rb'); if ($fp) { $imgData = fread($fp, filesize($imgPath)); $base64Data = base64_encode($imgData); return 'data:' . $imgInfo['mime'] . ';base64,' . $base64Data; } else { return false; } } $imgPath = 'test.jpg'; $base64Data = imgToBase64($imgPath); if (!$base64Data) { echo '图像文件读取失败'; exit; } ?>
Step 2: Construct the HTTP request data and send the request
<?php $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/clearness'; $access_token = 'your_access_token'; // 构造请求数据 $requestData = array( 'image' => $base64Data, ); $requestBody = http_build_query($requestData); // 发送POST请求 $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $requestBody); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/x-www-form-urlencoded', 'Content-Length: ' . strlen($requestBody), 'Access-Token: ' . $access_token, )); $response = curl_exec($curl); curl_close($curl); // 解析响应结果 $result = json_decode($response, true); if (isset($result['error_code'])) { echo '请求出错:' . $result['error_msg']; exit; } // 输出清晰度评分 echo '清晰度评分:' . $result['result']['score']; ?>
Step 3: Run the code and view the results
Save the above code as a PHP file and make sure the correct Access Token has been filled in. Run the PHP file in the command line or browser to get the image clarity score.
Summary:
This tutorial shows how to use PHP to connect to Baidu image definition recognition interface. By using this interface, we can easily judge the clarity of an image, so as to further analyze and process the image quality. I hope this tutorial can provide some help to everyone's development work in image processing.
The above is the detailed content of Simple tutorial: How to connect PHP to Baidu image definition recognition interface?. For more information, please follow other related articles on the PHP Chinese website!