Turn a text prompt into an image. Call an image model, save the bytes, and write prompts that actually control the result — subject, style, and composition.
Why: an image model takes a prompt and returns image bytes (or a URL) — the API shape mirrors text generation, but the output is binary you must decode and store. When: use it for illustrations, mockups, and assets; do not expect pixel-exact control or reliable text-in-images. Where: image calls are far slower and pricier than text, so budget and cache accordingly.
# pip install openai — image generation is provider-specific (OpenAI here).
from openai import OpenAI
import base64
client = OpenAI()
result = client.images.generate(
model="gpt-image-1",
prompt="A minimalist logo of a mint leaf inside a rounded square, flat design",
size="1024x1024",
)
img_bytes = base64.b64decode(result.data[0].b64_json)
with open("logo.png", "wb") as f:
f.write(img_bytes)Why: vague prompts give random results — naming subject, style, composition, and lighting narrows the model toward what you want. When: iterate the prompt like code, changing one variable at a time. Where: put the most important elements first; models weight early words more heavily.
WEAK: "a cat"
STRONG: "a ginger cat sitting on a windowsill, soft morning light,
shallow depth of field, photorealistic, 35mm"
Control levers:
subject -> what it is style -> photo / flat / 3D / watercolor
composition -> framing, angle lighting -> soft, dramatic, backlit
detail -> lens, palette, moodWhy: many image APIs also edit an existing image from a prompt (and a mask), which is how you do targeted changes instead of regenerating from scratch. When: use edits to change part of an image while keeping the rest; use the base image as context for consistency. Where: content policies apply — generations can be refused, so handle that like any other error.
# Edit an existing image with a prompt (and optional mask for the region).
result = client.images.edit(
model="gpt-image-1",
image=open("logo.png", "rb"),
prompt="Change the mint leaf to deep green and add a subtle drop shadow",
size="1024x1024",
)
edited = base64.b64decode(result.data[0].b64_json)
with open("logo-v2.png", "wb") as f:
f.write(edited)