Gemini API Image Generation at Scale: How-To
This guide shows you how to use the Gemini API to generate images programmatically, turning a single prompt into hundreds or thousands of images without manual intervention. You’ll learn the core workflow—authentication, request formatting, batching, rate-limit handling, and saving outputs—so you can build a scalable image generation pipeline.
What You’ll Need
- A Google Cloud project with the Vertex AI API enabled.
- An API key or service account credentials for authentication (the Gemini API uses an API key for simplicity, but Vertex AI uses OAuth2 tokens).
- Python 3.9+ installed, along with the
google-generativeailibrary (or the Vertex AI SDK if using Vertex). - Basic familiarity with Python and REST APIs.
- A text editor or IDE for writing your script.
Step-by-Step
- Set up your API key. Go to the Google AI Studio (or Google Cloud Console) and create an API key. Store it as an environment variable (e.g.,
GEMINI_API_KEY) to avoid hardcoding it in your script. - Install the SDK. In your terminal, run:
pip install google-generativeai. If you’re using Vertex AI, installgoogle-cloud-aiplatforminstead. - Import and configure the client. In your Python script, import the library and configure it with your API key:
import google.generativeai as genai import os genai.configure(api_key=os.environ["GEMINI_API_KEY"])
- Choose the image generation model. As of this writing, the model is
gemini-2.0-flash-preview-image-generation(or a newer version). Check the official docs for the latest model name. Set it as a variable for easy updates. - Write a function to generate one image. This function should take a prompt and a file path, call the API, and save the returned image. Example:
def generate_image(prompt, output_path): model = genai.GenerativeModel(model_name) response = model.generate_content(prompt) # The response contains image parts; extract and save the first one for part in response.parts: if part.inline_data: with open(output_path, "wb") as f: f.write(part.inline_data.data) return raise RuntimeError("No image returned") - Create a list of prompts. For scale, you’ll need many prompts. They can be static (from a CSV) or dynamically generated (e.g., varying a base prompt with different keywords). Store them in a list or read from a file.
- Loop through prompts with error handling. Iterate over your prompt list, call the function, and catch exceptions. Add a small delay (e.g.,
time.sleep(1)) to avoid hitting rate limits too quickly. - Implement concurrency (optional but recommended). Use Python’s
concurrent.futures.ThreadPoolExecutorto send multiple requests in parallel. The Gemini API supports concurrent requests, but be mindful of your quota. A thread pool of 5-10 workers is a safe start. - Handle rate limits and retries. Wrap your API calls in a retry loop with exponential backoff. The SDK may throw
ResourceExhaustederrors—catch them, wait, and retry. - Save outputs with meaningful filenames. Use an index or a hash of the prompt to avoid overwriting. For example:
output_001.png,output_002.png. - Monitor progress. Print a status message every N images, and log failures to a separate file so you can retry them later.
- Test with a small batch first. Run your script on 5 prompts before scaling to 1000. Verify the images look correct and the API behaves as expected.
Common Mistakes
- Not handling the response format correctly. The API returns a
GenerateContentResponseobject. Images are inresponse.partsasinline_data(withmime_typeanddata). Some developers try to accessresponse.textand get nothing. - Using a text-only model. Make sure you’re using a model that supports image generation, not just text output.
- Ignoring rate limits. Sending requests as fast as possible will trigger 429 errors. Always implement backoff.
- Hardcoding API keys in code. This is a security risk and can lead to accidental exposure if you commit the code.
- Not checking the response for safety filters. If the prompt violates content policies, the API may return a blocked response. Check
response.prompt_feedbackfor block reasons.
Tips
- Use a prompt template. For consistent style, define a base prompt and append variations (e.g., “in the style of a watercolor painting”).
- Cache your API key. Use environment variables or a secrets manager, not code.
- Batch requests with a thread pool. This can speed up generation 5-10x, but start with a low number of workers and increase gradually.
- Save images as PNG or JPEG. The API returns bytes; you can convert based on the MIME type.
- Log everything. Keep a CSV of prompt, output file, and timestamp for reproducibility.
- Check the official documentation. Model names and parameters change; always refer to the latest docs.
Troubleshooting
- API key not working. Ensure the key is valid and has billing enabled. Check that you’ve set the environment variable correctly and that you’re using the right endpoint (generativelanguage.googleapis.com for API key).
- No image in response. The model might have generated a safety block. Log
response.prompt_feedbackandresponse.finish_reason. If finish_reason isSAFETY, adjust your prompt. - Rate limit errors (429). Implement exponential backoff: start with a 1-second wait, double each retry, up to 60 seconds. Also reduce concurrency.
- Out of memory when saving many images. Write each image to disk immediately after receiving it, rather than storing all in memory.
- Images are distorted or wrong. Check your prompt for ambiguity. Add more specific details (subject, style, composition).
- SDK import errors. Ensure you installed the correct package and that your Python version is compatible.
Frequently Asked Questions
Can I generate multiple images per request?
No, the standard Gemini API generates one image per request. To get multiple images, you must send multiple requests.
What is the maximum resolution of generated images?
The default is 1024×1024, but some models may support higher resolutions. Check the model’s documentation for supported sizes.
How do I control the aspect ratio?
You can specify an aspect ratio in the prompt (e.g., “16:9”) or use the image_config parameter if the model supports it. Not all models expose this parameter.
Is there a free tier for the Gemini API?
Yes, Google offers a free tier with limited requests per minute. Check the pricing page for current limits. For large-scale use, you’ll need a paid plan.
Can I use the API for commercial purposes?
Yes, as long as you comply with Google’s terms of service. Images you generate are yours to use, but you must not use the API to create illegal or harmful content.
How do I get the image as a base64 string instead of bytes?
Use base64.b64encode(part.inline_data.data).decode('utf-8') to get a base64 string, which is useful for embedding in JSON.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.