Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the official OpenAI Python SDK to generate an image with client.images.generate(), then decode the returned base64 data and write it to a file in binary mode. For an existing image or a reference image, use client.images.edit() instead. The examples below use the GPT Image model family; confirm the current model name and supported settings in OpenAI’s live documentation before running them. The documentation was checked on September 29, 2026, and model names and API behavior can change.

What you need before you start

  • An OpenAI API key. Create one in the OpenAI dashboard and keep it private.
  • Python and the official OpenAI Python package. Install the current package with python -m pip install openai.
  • An environment variable named OPENAI_API_KEY containing your key. The SDK reads it when you initialize the client.

Do not paste the key into a script, commit it to a repository, or share it in logs. Set it in your shell before running the program. For example, on macOS or Linux, use export OPENAI_API_KEY="your-api-key". In PowerShell, use $env:OPENAI_API_KEY="your-api-key". These set the variable for the current shell session; use your operating system’s environment-variable settings if you need it to persist.

Generate an image and save it as a file

This complete example asks the API for an image, decodes the first returned image from base64, and saves the original bytes to fox.png. It uses the illustrative model name gpt-image-2; check the current model catalog and image reference for availability and compatible arguments before using it.

import base64
from openai import OpenAI

client = OpenAI()
result = client.images.generate(
    model="gpt-image-2",
    prompt="A small red fox reading a book in a sunlit library",
)

image_data = result.data[0].b64_json
if not image_data:
    raise RuntimeError("The response did not include base64 image data")

image_bytes = base64.b64decode(image_data)
with open("fox.png", "wb") as image_file:
    image_file.write(image_bytes)

print("Saved fox.png")

What each part does

  • OpenAI() initializes the official client, which reads OPENAI_API_KEY from the environment.
  • client.images.generate() submits a text prompt for image generation. The model name and optional parameters must be supported by that model.
  • result.data[0].b64_json is the base64-encoded image data in the documented cookbook pattern. base64.b64decode() converts it to bytes.
  • open(..., "wb") writes binary bytes without treating them as text or altering the image.

Run the script from the directory where you want the output file, or replace fox.png with an absolute or relative path such as output/fox.png. The destination directory must already exist; Python will not create missing parent directories automatically.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose an output format deliberately

The image API reference describes PNG, WebP, and JPEG output formats, along with size, quality, and background controls. Their accepted values and availability can depend on the model. Check the live reference before setting them. If you request WebP, save to a .webp filename; if you request JPEG, use a .jpg or .jpeg filename. A filename extension does not convert image data: request the format from the API and use the matching extension.

Keep the returned bytes unchanged when transparency matters. Converting an image to another format can change or discard alpha transparency; the exact result depends on the format and conversion process.

Choose between generating and editing

Task SDK method What to provide
Create an image from a text description client.images.generate() A prompt and a supported model; add only settings documented for that model.
Modify an existing image or use reference images client.images.edit() One or more image inputs and an instruction describing the desired edit.
Make a localized edit with a mask client.images.edit() An image, edit instruction, and mask where supported. Treat the mask as guidance, not a guarantee of an exact boundary.

Use generation when the output should be made from a prompt alone. Use editing when the result should be grounded in an existing image or reference. A mask can indicate where an edit should occur, but GPT Image may not follow its boundary with pixel-level precision; inspect the result and iterate if the edge matters.

Edit an existing image

The edit method is the right path when you want to provide source imagery. The exact accepted image-input and mask arguments are model- and API-reference dependent, so confirm the current Python reference before copying those argument names into production code. The basic shape is:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from openai import OpenAI

client = OpenAI()
with open("input.png", "rb") as source_image:
    result = client.images.edit(
        model="gpt-image-2",
        image=source_image,
        prompt="Keep the composition, but change the background to a quiet garden",
    )

This shows the intended operation, not a complete save-to-file program: once you have confirmed the current edit response shape, decode its returned base64 data and write it using the same binary-file pattern shown above. Check current model support for image inputs and masks, and do not assume an edit preserves every source detail exactly.

Settings, streaming, and sensitive inputs

Size, quality, format, and background

The image API exposes controls including output format, quality, size, and background. Pick them according to the destination—for example, a format suitable for the site or application that will display the file—and check the live reference for valid values for your chosen model. Do not assume a setting accepted by one model works with another.

Streaming partial images

The API reference documents partial-image events and a completion event containing base64 image content. Streaming is useful when an application needs to display progress or partial results. For a batch script whose only job is to save a finished image, a completed response is simpler; add streaming only if the interface benefits from incremental updates.

Data controls

If prompts or reference images may contain sensitive information, review OpenAI’s current data-controls documentation and your organization’s account settings before sending them. OpenAI lists image-generation models compatible with Zero Data Retention (ZDR), but model compatibility alone does not establish that ZDR is enabled for your organization. Confirm the active configuration rather than inferring it from the model name.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Handle output safely and reliably

  • Check that the response contains an image before decoding it. A response with no first item or no base64 data should be treated as an unexpected result, not written as an empty file.
  • Write bytes with wb, not text mode. Base64 is an encoding of binary data, not the image file itself.
  • Use a filename extension that matches the requested output format. Renaming a file does not transcode it.
  • For repeatable jobs, choose output paths deliberately and decide whether a new result should overwrite an existing file. The sample does overwrite fox.png.
  • Keep API credentials out of source control, and avoid printing secrets or sensitive prompts while diagnosing failures.

Troubleshooting common problems

The client cannot find the API key

Confirm that OPENAI_API_KEY is set in the same shell or process that runs Python. If you set it after opening a terminal or launching an editor, restart that process or set the variable in its environment. Keep the key private; do not solve this by hard-coding it in the script.

Python cannot import openai

Install the package into the same Python environment that runs the program: python -m pip install openai. If you use a virtual environment, activate it first. When several Python installations are present, use the interpreter-specific command associated with the one running your script.

The requested model or setting is rejected

Model availability and supported arguments can change. Verify the model name and each setting against the current model catalog and image API reference. Remove optional settings until the basic generation call works, then add supported controls one at a time.

The output file is missing, empty, or cannot be opened

Check the program’s working directory and the path you passed to open(). Ensure the parent directory exists and that the program can write there. Confirm that the response includes result.data[0].b64_json, decode that field, and write the decoded bytes in binary mode. If the file appears corrupt, verify that the extension matches the output format requested from the API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A mask does not confine the edit precisely

Mask boundaries are guidance rather than a pixel-exact promise for GPT Image. Review the result, refine the instruction or mask, and run another edit if needed. If a hard, deterministic edge is essential, use an image-processing step designed for exact compositing after generation.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is a website screenshot API, not an image-generation SDK: it captures web pages as images or PDFs and does not create pictures from prompts. If your task is to capture a webpage rather than generate artwork, one GET request can return a screenshot. See the ScreenshotNeo API documentation for the API details.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie or consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; those steps can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

Sign up for ScreenshotNeo’s free plan to capture up to 1,000 screenshots a month without a card.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Cost and implementation choices

Generation settings, model choice, output format, and streaming affect the implementation, but the supplied OpenAI documentation does not establish a specific per-image price or a universal performance figure. Check current API pricing and model documentation for your account before estimating a workload. For production use, test representative prompts, dimensions, and edit cases, and account for the time needed to inspect and potentially regenerate outputs. The simple example waits for a completed response; streaming is an option when progressive display is worth the added event-handling code.

Frequently Asked Questions

Does saving base64 data directly create a PNG?

It creates the image file in the format returned by the API; use an extension that matches the requested output format.

Can I rely on an edit mask for a perfectly exact edge?

No. The mask guides the edit, but exact boundary adherence is not guaranteed.

Is streaming required to generate an image?

No. It is an optional approach for applications that benefit from partial results; a completed response is enough for a basic save-to-file script.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.