Lesson 2 of 3 · AI Image & Video Creation

Generating Images

reading12 min

Let us get practical. The Images API is your primary tool for generating images programmatically. Whether you are building a product feature, automating content creation, or prototyping designs, this endpoint is where you start.

The Basic API Call

Python
from openai import OpenAI
client = OpenAI()

response = client.images.generate(
    model="gpt-image-1",
    prompt="A cozy coffee shop interior with warm lighting, exposed brick walls, and a chalkboard menu displaying 'Today's Special: Lavender Latte'",
    size="1024x1024",
    quality="high",
    n=1
)

image_url = response.data[0].url
print(f"Image URL: {image_url}")

That is it. One API call, one image. But the parameters you choose dramatically affect both quality and cost.

Parameters Deep Dive

Aspect Ratios and Resolutions

Choosing the right aspect ratio is not just about dimensions -- it affects composition. The model adjusts its framing based on the aspect ratio you request.

Use CaseRecommended SizeAspect Ratio
Social media post (Instagram)1024x10241:1
Social media story1024x15369:16 (vertical)
Blog header / banner1536x10243:2 (landscape)
YouTube thumbnail1792x102416:9 (wide)
Product image1024x10241:1
Hero section1792x102416:9 (wide)
Resolution Is Not Infinite

The maximum output resolution is constrained by the model. If you need images larger than the model's maximum output (currently around 1792x1024), you will need to upscale in post-processing. Tools like Real-ESRGAN or commercial upscalers can increase resolution while preserving quality.

Best Prompting Techniques

The difference between a mediocre image and a stunning one is almost always the prompt. Here is the structure that consistently produces good results:

[Subject] + [Setting/Context] + [Style/Mood] + [Lighting] + [Technical Details]

Mediocre prompt: "A dog in a park"

Better prompt: "A golden retriever playing fetch in a sunlit autumn park, leaves falling around it, warm golden hour lighting, shallow depth of field, photorealistic, shot from a low angle"

The Five Prompt Dimensions

  1. Subject: What is the main focus? Be specific about appearance, pose, and expression.
  2. Setting: Where is this happening? Indoor/outdoor, specific location, background elements.
  3. Style: Photorealistic, illustration, watercolor, 3D render, flat design, anime, editorial.
  4. Lighting: Natural light, studio lighting, golden hour, neon, dramatic shadows, soft diffused.
  5. Technical: Camera angle, depth of field, lens type, aspect ratio considerations.
Do

Front-load the most important elements of your prompt. The model pays more attention to the beginning. If the text on a sign is critical, mention it early: 'A storefront sign reading Morning Brew, cozy coffee shop exterior, warm lighting.'

Don't

Bury important details at the end of a long prompt. In a 200-word prompt, the model may give less weight to instructions at the end. Keep prompts focused -- 2-4 sentences is usually optimal.

Handling the Response

The API returns either a URL (temporary, expires in 60 minutes) or base64-encoded image data. For production use, always download and store the image immediately.

Python
import base64
import httpx
from pathlib import Path

# Option 1: URL response (default)
response = client.images.generate(
    model="gpt-image-1",
    prompt="A minimalist logo for a tech startup called 'Nexus'",
    size="1024x1024",
    n=1
)

# Download immediately -- URL expires in ~60 minutes
image_url = response.data[0].url
image_data = httpx.get(image_url).content
Path("nexus_logo.png").write_bytes(image_data)

# Option 2: Base64 response
response = client.images.generate(
    model="gpt-image-1",
    prompt="A minimalist logo for a tech startup called 'Nexus'",
    size="1024x1024",
    n=1,
    response_format="b64_json"
)

image_bytes = base64.b64decode(response.data[0].b64_json)
Path("nexus_logo.png").write_bytes(image_bytes)
URLs Expire

Image URLs returned by the API are temporary. They expire in approximately 60 minutes. Always download and store images immediately after generation. If you are building a user-facing application, save to your own storage (S3, Vercel Blob, Cloudflare R2) before serving to users. Never pass temporary OpenAI URLs directly to end users.

Batch Generation Pattern

For generating multiple images efficiently:

Python
import asyncio
from openai import AsyncOpenAI

async_client = AsyncOpenAI()

async def generate_batch(prompts, model="gpt-image-1"):
    tasks = [
        async_client.images.generate(
            model=model,
            prompt=prompt,
            size="1024x1024",
            quality="medium"
        )
        for prompt in prompts
    ]
    results = await asyncio.gather(*tasks, return_exceptions=True)
    return results

# Generate 10 product images in parallel
prompts = [
    f"Professional product photo of {product} on a clean white background, studio lighting"
    for product in product_list
]
images = asyncio.run(generate_batch(prompts))
Concept Card

beginner

Write 3 image generation prompts for a boutique hotel's marketing campaign, each targeting a different platform: (1) An Instagram square post showcasing the hotel pool. (2) A website hero banner (wide landscape) for the homepage. (3) A Pinterest pin (vertical) featuring the hotel restaurant. For each prompt, include all five prompt dimensions (subject, setting, style, lighting, technical) and specify the appropriate size parameter.