The Baidu Image Clarity Recognition API is a powerful feature provided by Baidu AI, which helps developers assess the clarity of an image and provide a clarity score. This tutorial will show you how to use PHP to integrate and call this API for quick image clarity analysis.
<?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 'Image file reading failed'; exit; } ?>
<?php $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/clearness'; $access_token = 'your_access_token'; // Construct 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 the response $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 in a PHP file, ensure that the correct Access Token is entered, and run the file. You will receive the image clarity score. You can check the result in your browser or command line.
In this tutorial, you've learned how to integrate Baidu's Image Clarity Recognition API with PHP. With the help of Baidu AI's powerful image processing capabilities, you can easily analyze and score image clarity. This is crucial for image quality evaluation and further processing.