Lompat ke konten

Pelajaran 16 ยท Images, Audio and Realtime

Image Generation and Editing

Generate and edit images with the OpenAI Image API and the image_generation tool, decode Base64 results, write clear prompts and review output safely.

Besides reading images, OpenAI's API can create them. You describe what you want and the model produces a picture. You can also give it existing images and ask for changes. This is useful for drafts, product mockups, illustrations and variations. It is less reliable when every detail must be exact, so plan to review the results.

You will learn the two ways to call image generation, how to save the output, and how to write and check requests.

Models

As of December 2026, OpenAI's model page lists GPT-Image models such as gpt-image-2.6-sunburst and gpt-image-2.6-flare, and also the 2.5 versions. Broadly, a "Sunburst" model focuses on detailed and precise work, and a "Flare" model on fast iteration. The image guide's examples also use gpt-image-2.5-sunburst.

Image model names change often. Older ones, including DALL-E and the first GPT image models, have been shut down or have announced shutdown dates. Check the model and deprecation pages, and keep the model ID in configuration.

Two ways to generate

The Image API is a direct call. Use it when your program just needs a picture.

Python
# Read-only
import base64
from openai import OpenAI

client = OpenAI()

result = client.images.generate(
    model="gpt-image-2.5-sunburst",
    prompt="A flat, friendly illustration of a bicycle repair stand, no text.",
)

image_bytes = base64.b64decode(result.data[0].b64_json)
with open("stand.png", "wb") as file:
    file.write(image_bytes)

The Responses API tool lets a general model decide to create an image during a conversation.

Python
# Read-only
response = client.responses.create(
    model="gpt-6.2-sol",
    input="Draw a simple icon for a recipe app.",
    tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)

images = [item.result for item in response.output
          if item.type == "image_generation_call"]

In both cases, the picture arrives as Base64 text. Decode it into bytes before you save it.

Edit an image

The edit operation takes one or more input images plus a prompt.

Python
# Read-only
result = client.images.edit(
    model="gpt-image-2.5-sunburst",
    image=[open("product.png", "rb")],
    prompt="Place the product on a plain light wooden table. Keep its label unchanged.",
)

Say what must stay the same as well as what should change. Even then, check carefully: edits can alter small details such as logos, text or shapes. Generation and editing also have settings, such as quality and output options. Their allowed values differ between models, so look them up in the current guide.

Save results safely

A generated file is data from outside your program. This runnable helper decodes Base64, checks that the bytes look like an image, and chooses a safe file name from a hash instead of from user text. The sample data is tiny and not a real picture.

Python Decode, check and name an image result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

If you ask for a different output format, check for that format's signature instead.

Write useful image prompts

A clear prompt usually names:

  1. Subject: what is in the picture.
  2. Style: photo, flat illustration, line drawing and so on.
  3. Composition: viewpoint, framing, background and empty space.
  4. Colors and mood.
  5. Constraints: for example "no text" or "leave the top third empty."
  6. Use: an app icon, a blog header, a product page.
TEXT
Flat vector-style illustration of a desk with a laptop and a plant,
seen from the front. Soft blue and warm yellow. Plain background,
wide empty area on the right for a headline. No text, no logos.

Change one thing at a time when you iterate, so you can see which change had which effect. If text inside an image must be exact, it is often better to add it with normal design tools or HTML.

Review before publishing

Check each image for:

  • Wrong or garbled text and numbers.
  • Anatomy, object or perspective errors.
  • Products that no longer look like the real item.
  • Brand marks or characters you have no right to use.
  • Biased or inappropriate depictions.

Be honest with users. Do not present a generated picture as a real photo of an event, a person or a product result. Follow OpenAI's usage policies, especially for images of real people. Rules about ownership and disclosure differ between countries, so get advice for commercial use.

Cost and user input

Image generation is usually priced very differently from short text calls, and size and quality affect it. Read the pricing page for current figures. Then protect the feature:

  • Limit how many images each user can create.
  • Show a clear error for refused prompts and do not retry them automatically.
  • Screen user prompts and results where needed. Safety and moderation explains one tool.
  • Send a hashed user identifier with the safety_identifier field on image requests.

Do not put a user's prompt into a file path, HTML page or command without escaping it. It is untrusted input like any other.

Handle failures and waiting

Image creation can take noticeably longer than a short text reply. Show progress, and for batches of images use a job queue so a web request does not stay open too long. Streaming of partial images is available in some cases; check the image guide.

A request can also be rejected, for example by safety rules. Show a neutral message and let the user change the request. Do not loop with small changes to get around a refusal. Technical errors can be retried with backoff, but remember that each successful generation costs money, so avoid automatic retries when you are not sure that the first one failed.

Keep a record for each image: the prompt, model ID, time, user ID and review status. It helps you reproduce your process and answer complaints. Decide how long to keep rejected and unused images, and delete them on schedule. Add alt text to every image you publish, written by a person who has looked at it.

Common mistakes

  • Publishing the first result without looking at it at full size.
  • Expecting an edit to keep a logo or label exactly the same without comparing it with the original.
  • Saving the Base64 text itself into an image file instead of decoding it first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In what form does the Image API result usually arrive in these examples?

    Decode b64_json into bytes before saving the file.
  2. 2. When editing an image, what helps most?

    Clear constraints help, but small details can still change, so review is needed.
  3. 3. How should you choose a file name for a user's generated image?

    Untrusted text in file paths can cause security problems.
  4. 4. Where should you check current image model names?

    Image models are replaced often, and old names stop working.

Summary

  • Use the Image API for direct creation, or the image_generation tool inside a response.
  • Results are Base64 data; decode and validate before saving.
  • Edits need clear constraints and careful review.
  • Prompt with subject, style, composition, limits and purpose.
  • Respect policies, rights and honesty, and limit usage.

Next: Speech and Realtime

Progres Anda disimpan di browser ini. Tidak perlu akun.