Current Location: Home> Latest Articles> How to Integrate Baidu Image Clarity Recognition API with PHP? A Detailed Tutorial

How to Integrate Baidu Image Clarity Recognition API with PHP? A Detailed Tutorial

M66 2025-06-12

Introduction

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.

Environment Setup

  1. PHP development environment (version required: PHP 5.6+)
  2. Baidu AI platform account and Access Token (refer to Baidu's official documentation for detailed instructions)
  3. The image file for analysis (in this tutorial, we will use "test.jpg")

Step 1: Get the Base64 Encoding of the Image via 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 'Image file reading failed';
    exit;
}
?>
    

Step 2: Construct 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';

// 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'];
?>
    

Step 3: Run the Code and View the Results

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.

Conclusion

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.