With the rapid development of the internet, image search technology has become increasingly popular. Baidu Image Search API offers powerful image search capabilities for developers. This article explains in detail how to integrate Baidu Image Search API using PHP, demonstrating the implementation of similar image retrieval.
Before starting to code, the following preparations are required:
Create a PHP file (e.g., search_image.php) and write the following code:
<?php
require_once 'AipImageSearch.php';
// Baidu Image Search API configuration
const APP_ID = 'your_app_id';
const API_KEY = 'your_api_key';
const SECRET_KEY = 'your_secret_key';
// Initialize Baidu Image Search client
$client = new AipImageSearch(APP_ID, API_KEY, SECRET_KEY);
// Load the image content to be searched
$sampleImage = file_get_contents('./sample.jpg'); // image path
$imageType = ''; // image format, e.g., jpg, png
$start = 0; // start position of results
$limit = 10; // number of results to return
// Send similar image search request
$result = $client->similarSearch($sampleImage, $imageType, $start, $limit);
// Process and display the search results
if (isset($result['result'])) {
foreach ($result['result'] as $item) {
echo 'Similar Image URL: ' . $item['url'] . "<br/>";
echo 'Similarity Score: ' . $item['score'] . "<br/>";
echo 'Thumbnail URL: ' . $item['thumbnail'] . "<br/>";
echo 'Image Library ID: ' . $item['cont_sign'] . "<br/>";
echo "<hr/>";
}
} else {
echo 'Similar image search failed';
}
?>
Be sure to replace your_app_id, your_api_key, and your_secret_key with the actual credentials obtained from the Baidu developer platform.
Place the image to be searched (sample.jpg in the example) and the PHP file in the same directory. Access the PHP file via browser, e.g., http://localhost/search_image.php, to see the similar image search results.
This article has explained the basic process of integrating Baidu Image Search API with PHP and provided a detailed code example to implement similar image retrieval. Developers can build on this foundation to expand functionality for various use cases. We hope this guide helps you better understand and utilize Baidu Image Search API.