How to Generate Images in Claude Code (2026)
Claude Code is fantastic at writing code, fixing bugs, and explaining things. But ask it to draw you a picture and it'll politely tell you it can't — it's a text-based tool with no built-in image generation. Here's the
Claude Code is fantastic at writing code, fixing bugs, and explaining things. But ask it to draw you a picture and it'll politely tell you it can't — it's a text-based tool with no built-in image generation.
Here's the good news: you can teach it. In about ten minutes, you can set Claude Code up with a third-party image API, and from then on you just say "generate an image of a sunset over mountains" and it handles everything. Your API key stays tucked away in a file Claude reads but never repeats back to you.
We'll use Google's Gemini API as our example in this guide, but nothing here is Gemini-specific — OpenAI, Stability AI, Replicate, or any other image API with an HTTP endpoint works exactly the same way. Swap the key and the endpoint, keep everything else.
This guide assumes you've never done anything like this before. Let's go step by step.
What You'll Need
Three things:
- Claude Code installed and working (if you can open it and chat, you're good)
- An API key for an image generation API — we'll use Google's Gemini in this guide, but any provider works
- A project folder — any folder where you run Claude Code
That's it. No complicated setup.
Step 1: Get Your Gemini API Key
Google's Gemini API can generate images. To use it (or any other provider — the steps are the same idea everywhere: sign up, create a key, copy it):
- Go to aistudio.google.com and sign in with your Google account.
- Click Get API Key (usually in the left sidebar or top menu).
- Click Create API Key. Google will generate a long string of letters and numbers — that's your key.
- Copy it somewhere safe for the next two minutes. You'll paste it into a file in the next step, then you won't need to look at it again.
A note on pricing: Google AI Studio has historically offered a free tier, but what's included can change — check their current pricing page to confirm image generation is covered before you start generating dozens of images. The same goes for any provider: know what each image costs you before you scale up.
Treat this key like a password. Anyone with your key can generate images on your dime (or burn through your free quota). You'll never paste it into a chat window — not even to Claude.
Step 2: Create Your .env File
A .env file is just a plain text file that holds secrets like API keys. Programs read it; humans rarely open it. Keeping your key here instead of in your code or chat history is standard practice.
- In your project folder (the same folder where you run Claude Code), create a file called exactly
.env— nothing before the dot. - Open it in any text editor and add one line:
GEMINI_API_KEY=your-actual-key-goes-here
Replace your-actual-key-goes-here with the key you copied from AI Studio. No quotes, no spaces around the equals sign.
- Save the file.
One more critical step: if your project uses git, make sure .env never gets committed. Create (or open) a file called .gitignore in the same folder and add this line:
.env
That's it. Your key now lives in one place, out of your code and out of your chat history.
Step 3: Tell Claude Code About Your Setup
Here's where the magic happens. Open Claude Code in your project folder and send it a message like this:
I put my Gemini API key in the
.envfile in this project asGEMINI_API_KEY. From now on, whenever I ask you to generate an image, use that key with the Gemini image generation API to create it. Read the key from the.envfile yourself — never ask me for it, and never print it, display it, or paste it into the chat.
That's the whole instruction. You're establishing three rules:
-
Where the key lives — in
.env, under the nameGEMINI_API_KEY. - What to do with it — use it for image generation whenever you ask.
- What never to do with it — show it to you or anyone else.
Claude Code will confirm it understands. From this point on, the setup is permanent for this project — you only do this once.
Optional: Make It Permanent with CLAUDE.md
If you want this to survive across sessions without re-explaining, add the same instruction to a CLAUDE.md file in your project root. Claude Code reads this file automatically every time it starts. Just create CLAUDE.md and write:
## Image Generation
- The Gemini API key is stored in `.env` as `GEMINI_API_KEY`.
- When I ask for an image, generate it using the Gemini image API
(model `gemini-3.1-flash-image`) with that key.
- Never display, repeat, or log the API key.
Now every future Claude Code session in this folder knows the deal from the start.
Step 4: Generate Your First Image
Just ask. Try something like:
Generate an image of a cozy cabin in the woods at sunset, warm light in the windows.
Claude Code will get to work. Here's roughly what happens behind the scenes:
- It reads your
.envfile to get the key (silently — you won't see the key). - It writes a small script that calls the Gemini API with your prompt.
- It runs the script, which sends your prompt to Google's image model.
- It saves the resulting image into your project folder (usually as a
.pngfile) and tells you where it is.
A few seconds later, you'll have an actual image file sitting in your folder. Open it and take a look.
Want another? Just keep asking:
Now generate a logo concept for a coffee shop called "Moonbeam Roasters" — minimalist, crescent moon, warm browns.
Each image lands in your project folder, ready to use.
How It Works Under the Hood
You don't need to understand this to use it, but it's nice to know what's happening — and it demystifies why this approach is so flexible.
When you ask for an image, Claude Code typically writes a short Python script that looks something like this:
import os
import base64
import requests
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv("GEMINI_API_KEY")
response = requests.post(
"https://generativelanguage.googleapis.com/v1beta/models/"
"gemini-3.1-flash-image:generateContent?key=" + api_key,
headers={"Content-Type": "application/json"},
json={
"contents": [{"parts": [{"text": "a cozy cabin in the woods at sunset"}]}],
"generationConfig": {"responseModalities": ["IMAGE"]},
},
)
data = response.json()
for part in data["candidates"][0]["content"]["parts"]:
if "inlineData" in part:
with open("cabin-sunset.png", "wb") as f:
f.write(base64.b64decode(part["inlineData"]["data"]))
The script loads your key from .env, sends your prompt to Gemini's image model, gets back image data, and saves it as a PNG. Claude handles all of this for you — you'll usually never need to write or even look at this code. But now you know there's no magic involved, just an API call.
The beauty of this setup: it works with any image API, not just Gemini. If you'd rather use OpenAI's image model, Stability AI, or anything else with an HTTP API, the same pattern applies — key in .env, instruction to Claude, done.
Your API Key Stays Safe
This deserves its own section because it's the part beginners worry about most — rightly so.
Here's what protects your key in this setup:
-
It's in
.env, not in chat. You never typed the key into Claude Code. Claude read it from the file directly. -
Claude was told never to display it. The instruction in Step 3 (or your
CLAUDE.md) explicitly forbids printing the key. Claude respects this — it will use the key silently in API calls without ever echoing it. -
.gitignorekeeps it out of version control. If you push your project to GitHub, the.envfile stays on your machine.
One thing to watch: if you ever ask Claude to "show me the script you used," the script it shows you will reference os.getenv("GEMINI_API_KEY") — the variable name, not the actual key. That's exactly what you want.
Tips for Better Images
Once the basics work, these small habits make a big difference:
- Be specific in your prompts. "A dog" gives you a generic dog. "A watercolor painting of a golden retriever puppy sleeping in a sunbeam, soft brushstrokes" gives you something you'll actually want to keep.
- Mention style. Photorealistic, cartoon, oil painting, pixel art, minimalist logo — the model follows style cues well.
- Ask for variations. "Give me three versions of this" works fine. Claude will generate them one after another.
- Iterate. Don't like the result? Say what to change: "same thing but at night" or "make it wider, more like a banner." Each round is a new API call.
- Name your files. "Save this one as hero-banner.png" keeps your folder organized instead of filling up with generic names.
Troubleshooting
"Claude says it can't find the key." Make sure the .env file is in the same folder where you're running Claude Code, and that the variable is named exactly GEMINI_API_KEY (all caps, underscores). Check for typos and stray spaces.
"The API returns an error." The most common cause is an invalid or expired key. Go back to AI Studio, generate a fresh key, and update your .env. Also check your usage against your plan's quota — if you've hit a limit, that's your culprit.
"The image looks wrong." That's a prompting issue, not a setup issue. Try describing what you want in more detail — subject, style, lighting, mood. Image models are literal; they draw what you describe.
"Claude printed my key!" This shouldn't happen if you gave the instruction from Step 3. If it ever does, immediately go to AI Studio and revoke/regenerate your key, update .env, and remind Claude of the rule.
Wrapping Up
That's the whole setup: key from AI Studio, one line in .env, one instruction to Claude Code. Ten minutes of setup, and from then on generating images is as easy as describing what you want.
What I love about this approach is that nothing is locked in. Swap Gemini for another provider later? Just change the key and tell Claude which API to call. The pattern — secrets in .env, instructions in plain English — works for any API you want Claude Code to use, not just image generation.
Now go make something. Start with that cabin at sunset.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.