pip install -q -U google-generativeai pillow

 import google.generativeai as genai

import os

import base64

from PIL import Image

from io import BytesIO


# Install the google-generativeai library

# (You'll need to run this in your terminal/bash)

# pip install -q -U google-generativeai pillow


# Configure your API key (replace with your actual API key)

GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") # Consider using environment variables for security.

if not GOOGLE_API_KEY:

    raise ValueError("Please set the GOOGLE_API_KEY environment variable.")


genai.configure(api_key=GOOGLE_API_KEY)


def generate_image(prompt, model_name="gemini-pro-vision"):  # Use gemini-pro-vision for image generation.

    """Generates an image based on the given prompt using Gemini Pro Vision.


    Args:

        prompt: The text prompt for image generation.

        model_name: The name of the Gemini model to use.


    Returns:

        A PIL Image object, or None if an error occurs.

    """

    model = genai.GenerativeModel(model_name)


    try:

        response = model.generate_content(prompt)

        # Gemini Vision returns a list of parts, one of which is a data part.

        for part in response.parts:

          if part.mime_type == "image/png":

            image_bytes = base64.b64decode(part.data)

            image = Image.open(BytesIO(image_bytes))

            return image

        return None  # No image was found in the response.

    except Exception as e:

        print(f"An error occurred: {e}")

        return None


def save_image(image, filename="generated_image.png"):

    """Saves a PIL Image object to a file.


    Args:

        image: The PIL Image object to save.

        filename: The filename to save the image as.

    """

    if image:

        image.save(filename)

        print(f"Image saved as {filename}")

    else:

        print("No image to save.")


# Example usage

prompt = "A futuristic cityscape at sunset, with flying cars."

generated_image = generate_image(prompt)


if generated_image:

    save_image(generated_image, "futuristic_city.png")


prompt2 = "A photorealistic cat wearing a tiny hat."

generated_image2 = generate_image(prompt2)


if generated_image2:

    save_image(generated_image2, "cat_hat.png")

Comments