Introduction:
The Baidu Image Clarity Recognition API is a powerful image processing feature provided by Baidu AI Open Platform. With this API, we can leverage Baidu AI's powerful algorithms to assess the clarity of an image and obtain a corresponding score. This tutorial will show how to integrate Baidu's Image Clarity Recognition API using PHP code.
<?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 'Failed to read image file'; exit; } ?>
<?php $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/clearness'; $access_token = 'your_access_token'; // Insert your Access Token here // Build request data $requestData = array( 'image' => $base64Data, ); $requestBody = http_build_query($requestData); // Send POST request $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); // Parse response result $result = json_decode($response, true); if (isset($result['error_code'])) { echo 'Request error: ' . $result['error_msg']; exit; } // Output clarity score echo 'Clarity score: ' . $result['result'][0]['score']; ?>
Save the above code as a PHP file and ensure you have filled in the correct Access Token. Run the PHP file in the command line or browser, and you will get the image's clarity score.
This tutorial demonstrated how to integrate Baidu's Image Clarity Recognition API using PHP. By using this API, we can easily assess the clarity of an image and perform further analysis and processing on its quality. We hope this tutorial provides valuable assistance for your image processing development work.