Certainly! Below is a complete HTML file that allows users to upload an image, sends the image to the Google Gemini (GenAI) API for analysis, and displays the resulting description. Please note that embedding your API key directly in client-side code is not secure and can expose your key to unauthorized use. For production applications, it's recommended to handle API requests on the server side.
However, for demonstration purposes, here's how you can create a simple HTML page to achieve the desired functionality:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Analyzer with Google Gemini</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 40px;
background-color: #f5f5f5;
}
.container {
max-width: 600px;
margin: auto;
background: #ffffff;
padding: 30px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.preview {
margin-top: 20px;
text-align: center;
}
.preview img {
max-width: 100%;
height: auto;
border-radius: 8px;
}
#result {
margin-top: 20px;
padding: 15px;
background-color: #e7f3fe;
border-left: 6px solid #2196F3;
border-radius: 4px;
}
button {
padding: 10px 20px;
background-color: #2196F3;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0b7dda;
}
</style>
</head>
<body>
<div class="container">
<h2>Image Analyzer using Google Gemini</h2>
<input type="file" id="imageInput" accept="image/*"><br><br>
<button id="analyzeBtn">Analyze Image</button>
<div class="preview" id="preview"></div>
<div id="result"></div>
</div>
<script>
document.getElementById('imageInput').addEventListener('change', previewImage);
document.getElementById('analyzeBtn').addEventListener('click', analyzeImage);
function previewImage(event) {
const preview = document.getElementById('preview');
preview.innerHTML = '';
const file = event.target.files[0];
if (file) {
const img = document.createElement('img');
img.src = URL.createObjectURL(file);
img.onload = () => URL.revokeObjectURL(img.src); // Free memory
preview.appendChild(img);
}
}
async function analyzeImage() {
const fileInput = document.getElementById('imageInput');
const resultDiv = document.getElementById('result');
resultDiv.innerHTML = 'Analyzing...';
if (!fileInput.files || !fileInput.files[0]) {
alert('Please upload an image first.');
resultDiv.innerHTML = '';
return;
}
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = async function() {
const base64Image = reader.result.split(',')[1]; // Remove data:image/...;base64,
// Prepare the payload as per the example provided
const payload = {
prompts: ["Describe this image:"],
imageParts: [
{
inlineData: {
data: base64Image,
mimeType: file.type
}
}
]
};
try {
const response = await fetch('https://api.genai.google/gemini-pro-vision/v1/generate', { // Replace with the correct API endpoint
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY_HERE' // Replace with your actual API key
},
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(`Error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
// Assuming the response structure has a 'response.text' field
// Adjust according to the actual API response structure
const description = data.response.text;
resultDiv.innerHTML = `<strong>Analysis Result:</strong><br>${description}`;
} catch (error) {
console.error('Error analyzing image:', error);
resultDiv.innerHTML = `Failed to analyze image: ${error.message}`;
}
};
reader.readAsDataURL(file);
}
</script>
</body>
</html>
Explanation of the Code
-
HTML Structure:
- File Input: Allows users to select an image from their device.
- Analyze Button: Triggers the image analysis process.
- Preview Section: Displays the uploaded image.
- Result Section: Shows the analysis result returned by the API.
-
Styling:
- Basic CSS is added to make the interface user-friendly and visually appealing.
-
JavaScript Functionality:
- Image Preview: When a user selects an image, it is displayed on the page.
- Image Analysis:
- Reads the selected image file and encodes it in Base64.
- Constructs the payload as per your provided Node.js example.
- Sends a POST request to the Google Gemini API endpoint with the necessary headers, including the API key.
- Processes the response and displays the analysis result.
Important Considerations
-
API Endpoint:
- Replace
'https://api.genai.google/gemini-pro-vision/v1/generate' with the actual Google Gemini API endpoint provided in the documentation.
-
API Key Security:
- Do Not expose your API key in client-side code for production applications.
- To secure your API key:
- Implement a backend server (using Node.js, Python, etc.) to handle API requests.
- The frontend (HTML/JavaScript) would send the image to your backend server.
- The backend server processes the image, communicates with the Google Gemini API using the API key, and returns the result to the frontend.
-
CORS (Cross-Origin Resource Sharing):
- Depending on the API's CORS policy, you might encounter cross-origin issues when making requests directly from the client. Handling requests on the server side can help bypass such restrictions.
-
Error Handling:
- The provided code includes basic error handling to notify users if something goes wrong during the analysis process.
-
Response Structure:
- Ensure that you adjust the way you parse the API response (
data.response.text) based on the actual structure returned by the Google Gemini API.
Next Steps for Production
-
Set Up a Backend Server:
- Use Node.js, Python, or another server-side technology to handle image uploads and communicate securely with the Google Gemini API.
-
Secure Storage of API Keys:
- Store your API keys in environment variables or secure storage solutions, never hard-code them into your frontend code.
-
Implement Authentication:
- If your application requires user authentication, implement appropriate security measures to protect user data and API access.
-
Enhance User Experience:
- Add loading indicators, better error messages, and possibly support for multiple image formats and sizes.
By following the above steps and considerations, you can create a secure and efficient image analysis tool using Google Gemini.