Simple Connect with your website or app. Easily integrated with Node.js, .NET Core, PHP, and Java – Complete documentation provided.
The AI - Image Search Engine is a powerful solution that allows website owners to integrate advanced image search functionality into their platforms with minimal setup. By leveraging artificial intelligence, this tool enables users to upload images and search for related products within the website's database.
Designed to be simple and effective, the AI - Image Search Engine offers a plug-and-play integration with just one .js file and a few lines of server-side code. It supports seamless integration into any website, making it a perfect solution for e-commerce platforms, product catalogs, or any site with visual search needs.
Watch the demo to see AI ImageMatch Finder in action—snap, upload, and discover products instantly!
The AI - Image Search Engine offers a rich set of features that make it easy for website owners to integrate advanced image-based search capabilities. This powerful solution allows users to upload images and search for related products with just a few clicks, enhancing the shopping and browsing experience.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
To integrate the AI - Image Search Engine with your application:
To generate a Google Cloud Vision API key and save it in a local folder:
GOOGLE_APPLICATION_CREDENTIALS
environment variable to point to the location of your JSON key file.
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your-service-account-file.json"
[HttpPost] public async TaskProcessImage([FromBody] ImageRequest request) { if (string.IsNullOrEmpty(request.Image)) { return BadRequest("No image data provided."); } string tempFilePath = null; try { // Decode Base64 image var base64Data = request.Image.Substring(request.Image.IndexOf(',') + 1); byte[] imageBytes; try { imageBytes = Convert.FromBase64String(base64Data); } catch { return BadRequest("Invalid Base64 image data."); } // Save the image temporarily tempFilePath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.jpg"); await System.IO.File.WriteAllBytesAsync(tempFilePath, imageBytes); // Set environment variable for credentials dynamically within the method Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", _credentialsPath); // Authenticate and create Vision API client var client = ImageAnnotatorClient.Create(); // Read the image var image = Google.Cloud.Vision.V1.Image.FromFile(tempFilePath); // Analyze image var response = await client.DetectLabelsAsync(image); // Extract labels var labels = response.Select(label => label.Description).ToList(); // Handle empty label case if (!labels.Any()) { return Ok(new { Message = "No labels detected in the image." }); } // Search for products matching the detected labels var matchingProducts = SearchProductsByLabels(labels); // Return the response with matching products and labels //return Ok(new { Labels = labels, MatchingProducts = matchingProducts }); return Json(new { label = labels, products = matchingProducts, count=matchingProducts.Count }); // Return the list as a JSON response } catch (Exception ex) { // Log exception (you can replace this with proper logging) Console.WriteLine($"Error processing image: {ex.Message}"); return BadRequest($"Error processing image: {ex.Message}"); } finally { // Cleanup temporary file if (!string.IsNullOrEmpty(tempFilePath) && System.IO.File.Exists(tempFilePath)) { System.IO.File.Delete(tempFilePath); } } }
"No image data provided."]); } $tempFilePath = null; try { // Decode Base64 image $base64Data = substr($imageBase64, strpos($imageBase64, ',') + 1); $imageBytes = base64_decode($base64Data); if ($imageBytes === false) { return json_encode(["error" => "Invalid Base64 image data."]); } // Save the image temporarily $tempFilePath = sys_get_temp_dir() . '/' . uniqid() . '.jpg'; file_put_contents($tempFilePath, $imageBytes); // Set Google Cloud Vision API credentials (ensure that the credentials JSON file path is set properly) putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-service-account-file.json'); // Create Vision API client $client = new ImageAnnotatorClient(); // Read the image $image = file_get_contents($tempFilePath); // Analyze image labels $response = $client->labelDetection($image); $labels = $response->getLabelAnnotations(); // Extract label descriptions $labelDescriptions = []; foreach ($labels as $label) { $labelDescriptions[] = $label->getDescription(); } // Handle empty label case if (empty($labelDescriptions)) { return json_encode(["message" => "No labels detected in the image."]); } // Search for products matching the detected labels (implement your own search function) $matchingProducts = searchProductsByLabels($labelDescriptions); // Return the response with matching products and labels return json_encode([ 'labels' => $labelDescriptions, 'products' => $matchingProducts, 'count' => count($matchingProducts) ]); } catch (Exception $ex) { // Log the error (you can replace this with proper logging) error_log("Error processing image: " . $ex->getMessage()); return json_encode(["error" => "Error processing image: " . $ex->getMessage()]); } finally { // Cleanup temporary file if ($tempFilePath && file_exists($tempFilePath)) { unlink($tempFilePath); } } } function searchProductsByLabels($labels) { // Implement your logic to search for products based on the labels // Example: return an array of matching products (this should be replaced with actual logic) return [ ["name" => "Product 1", "description" => "Product matching label 1"], ["name" => "Product 2", "description" => "Product matching label 2"] ]; } // Example usage: $imageBase64 = $_POST['image'] ?? ''; // Get the image from POST data echo processImage($imageBase64); ?>
const fs = require('fs-extra'); const path = require('path'); const { ImageAnnotatorClient } = require('google-cloud/vision'); const uuid = require('uuid'); const base64Img = require('base64-img'); // Create a Vision API client const client = new ImageAnnotatorClient(); async function processImage(imageBase64) { if (!imageBase64) { return { error: "No image data provided." }; } let tempFilePath = null; try { // Decode Base64 image const base64Data = imageBase64.split(',')[1]; // Remove the data URL part const imageBuffer = Buffer.from(base64Data, 'base64'); // Save the image temporarily tempFilePath = path.join(__dirname, `${uuid.v4()}.jpg`); await fs.writeFile(tempFilePath, imageBuffer); // Set Google Cloud Vision API credentials (ensure this is set properly) process.env.GOOGLE_APPLICATION_CREDENTIALS = '/path/to/your-service-account-file.json'; // Perform label detection on the image const [result] = await client.labelDetection(tempFilePath); const labels = result.labelAnnotations; // Extract label descriptions const labelDescriptions = labels.map(label => label.description); // Handle empty label case if (labelDescriptions.length === 0) { return { message: "No labels detected in the image." }; } // Search for products matching the detected labels (implement your own search function) const matchingProducts = searchProductsByLabels(labelDescriptions); // Return the response with matching products and labels return { labels: labelDescriptions, products: matchingProducts, count: matchingProducts.length }; } catch (error) { console.error("Error processing image:", error.message); return { error: "Error processing image: " + error.message }; } finally { // Cleanup temporary file if (tempFilePath && fs.existsSync(tempFilePath)) { await fs.remove(tempFilePath); } } } function searchProductsByLabels(labels) { // Implement your logic to search for products based on the labels // Example: return an array of matching products (this should be replaced with actual logic) return [ { name: "Product 1", description: "Product matching label 1" }, { name: "Product 2", description: "Product matching label 2" } ]; } // Example usage: const imageBase64 = 'your-base64-image-data-here'; // Get the image Base64 data processImage(imageBase64).then(response => { console.log(response); }).catch(error => { console.error(error); });
package com.example.imageprocessor.controller; import com.google.cloud.vision.v1.ImageAnnotatorClient; import com.google.cloud.vision.v1.Image; import com.google.cloud.vision.v1.AnnotateImageRequest; import com.google.cloud.vision.v1.AnnotateImageResponse; import com.google.cloud.vision.v1.Feature; import com.google.protobuf.ByteString; import org.apache.commons.io.FileUtils; import org.springframework.web.bind.annotation.*; import org.springframework.http.ResponseEntity; import org.springframework.util.Base64Utils; import org.springframework.beans.factory.annotation.Value; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; RestController RequestMapping("/api") public class ImageProcessorController { Value("${google.cloud.credentials}") private String credentialsPath; PostMapping("/processImage") public ResponseEntity processImage(RequestBody ImageRequest request) { if (request.getImage() == null || request.getImage().isEmpty()) { return ResponseEntity.badRequest().body("No image data provided."); } String tempFilePath = null; try { // Decode the Base64 image String base64Data = request.getImage().split(",")[1]; byte[] imageBytes = Base64Utils.decodeFromString(base64Data); // Save the image temporarily tempFilePath = "temp-" + System.currentTimeMillis() + ".jpg"; File tempFile = new File(tempFilePath); FileUtils.writeByteArrayToFile(tempFile, imageBytes); // Set Google Cloud Vision API credentials System.setProperty("GOOGLE_APPLICATION_CREDENTIALS", credentialsPath); // Create a Vision API client try (ImageAnnotatorClient visionClient = ImageAnnotatorClient.create()) { // Build the image ByteString imgBytes = ByteString.readFrom(new File(tempFilePath).toPath()); Image img = Image.newBuilder().setContent(imgBytes).build(); // Perform label detection Feature feature = Feature.newBuilder().setType(Feature.Type.LABEL_DETECTION).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder() .addFeatures(feature) .setImage(img) .build(); Listrequests = new ArrayList<>(); requests.add(request); // Detect labels List responses = visionClient.batchAnnotateImages(requests).getResponsesList(); if (responses.isEmpty() || responses.get(0).getLabelAnnotationsList().isEmpty()) { return ResponseEntity.ok("No labels detected in the image."); } // Extract labels List labels = new ArrayList<>(); responses.get(0).getLabelAnnotationsList().forEach(label -> labels.add(label.getDescription())); // Handle matching products (implement your logic to search for products based on labels) List matchingProducts = searchProductsByLabels(labels); // Return the response with labels and matching products return ResponseEntity.ok(new ImageResponse(labels, matchingProducts)); } catch (Exception e) { return ResponseEntity.status(500).body("Error processing image: " + e.getMessage()); } } catch (IOException e) { return ResponseEntity.status(500).body("Error decoding Base64 image data."); } finally { // Clean up temporary file if (tempFilePath != null) { File tempFile = new File(tempFilePath); if (tempFile.exists()) { tempFile.delete(); } } } } private List searchProductsByLabels(List labels) { // Implement your logic to search for products based on the detected labels // Example of a mock search List products = new ArrayList<>(); for (String label : labels) { products.add(new Product(label, "Product matching " + label)); } return products; } }
Introducing the AI Image Search Engine for visual product search using Google Vision API.
Future versions will continue to enhance the donation box system with additional features such as:
Your website is a tireless employee, working around the clock, 24 hours a day, 7 days a week, without rest or break. It is the face of your business, representing you to the world, and it needs to be the best it can be. That's why you can trust the expert team at AM-Technology to create the ultimate employee for your business - a website that works for you, day and night.
Contact us