import React, { useState } from 'react'; // Main App component for the AI Image Generator const App = () => { const [prompt, setPrompt] = useState(''); // State to store the user's text prompt const [imageUrl, setImageUrl] = useState(''); // State to store the generated image URL const [loading, setLoading] = useState(false); // State to manage loading indicator const [error, setError] = useState(''); // State to store any error messages // Function to handle image generation const generateImage = async () => { setError(''); // Clear any previous errors setImageUrl(''); // Clear previous image setLoading(true); // Set loading to true try { // Define the payload for the image generation API call // Using imagen-3.0-generate-002 as specified const payload = { instances: { prompt: prompt }, parameters: { "sampleCount": 1 } // Request one image }; // API key is left empty; it will be provided by the Canvas runtime const apiKey = ""; const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/imagen-3.0-generate-002:predict?key=${apiKey}`; // Make the fetch call to the image generation API const response = await fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); // Check if the response was successful if (!response.ok) { const errorData = await response.json(); throw new Error(`API error: ${errorData.error?.message || response.statusText}`); } const result = await response.json(); // Check if predictions exist and contain base64 encoded image data if (result.predictions && result.predictions.length > 0 && result.predictions[0].bytesBase64Encoded) { // Construct the image URL from the base64 data const generatedImageUrl = `data:image/png;base64,${result.predictions[0].bytesBase64Encoded}`; setImageUrl(generatedImageUrl); // Set the image URL to display } else { setError('No image data received from the API. Please try again.'); } } catch (err) { console.error('Error generating image:', err); setError(`Failed to generate image: ${err.message}. Please try a different prompt.`); } finally { setLoading(false); // Set loading to false regardless of success or failure } }; // Function to handle downloading the image const downloadImage = () => { if (imageUrl) { const link = document.createElement('a'); link.href = imageUrl; link.download = 'ai-generated-image.png'; // Set the download filename document.body.appendChild(link); link.click(); document.body.removeChild(link); } }; return (

AI Image Generator

{/* Disclaimer for Blogger/External Hosting */}

Important Note for Blogger/External Hosting:

This AI image generator uses a powerful API that requires a secure key. It will work here in this interactive environment. However, if you copy this code to a static website like Blogger, the image generation functionality will **NOT work** because the API key cannot be securely handled in that environment. AI image generation services also typically incur costs per use.

{error && (

{error}

)} {imageUrl && (

Generated Image:

Generated by AI { e.target.onerror = null; e.target.src="https://placehold.co/400x400/FF6347/FFFFFF?text=Image+Load+Error"; setError("Failed to load generated image. It might be corrupted or invalid."); }} />
)}
); }; export default App;