|
| 1 | +# Generate Images in Python With OpenAI's GPT Image API |
| 2 | + |
| 3 | +Learn to use the OpenAI Python library to create images with the GPT Image models. In the associated tutorial on [generating images with the OpenAI API](https://realpython.com/generate-images-openai/), you'll create images from text prompts, tune the size and quality of your results, and edit an image with a follow-up prompt. You'll learn how to interact with the Images API and incorporate this functionality into your Python scripts. |
| 4 | + |
| 5 | +## Setup |
| 6 | + |
| 7 | +Create and activate a virtual environment, then install the `openai` package: |
| 8 | + |
| 9 | +```console |
| 10 | +$ python --version |
| 11 | +Python 3.14.6 |
| 12 | +$ python -m venv venv |
| 13 | +$ source venv/bin/activate |
| 14 | +(venv) $ python -m pip install openai==3.13.0 |
| 15 | +``` |
| 16 | + |
| 17 | +You need to be on Python 3.10 or higher. |
| 18 | + |
| 19 | +The scripts read your API key from the `OPENAI_API_KEY` environment variable: |
| 20 | + |
| 21 | +```console |
| 22 | +(venv) $ export OPENAI_API_KEY="<your-key-value-here>" |
| 23 | +``` |
| 24 | + |
| 25 | +## Create and Edit Images |
| 26 | + |
| 27 | +Follow the instructions in [the tutorial](https://realpython.com/generate-images-openai/) to create images from text prompts, edit an image with a follow-up prompt, and convert a Base64 JSON response to a PNG image file. |
| 28 | + |
| 29 | +You can find the code for each of these steps in dedicated scripts: |
| 30 | + |
| 31 | +- `create_png.py`: Create an image from a text prompt and write it straight to a PNG file. |
| 32 | +- `create.py`: Create an image from a text prompt and save the whole JSON response to a file. |
| 33 | +- `convert.py`: Convert a Base64-encoded PNG image delivered in a JSON response to a PNG image file. |
| 34 | +- `edit.py`: Read Base64-encoded image data and make an API request to edit that image with a prompt. |
| 35 | + |
| 36 | +In the tutorial, you'll walk through each of these scripts and their functionality and output in more detail. |
| 37 | + |
| 38 | +Note that `convert.py` and `edit.py` read a saved response from the `responses/` directory. Run `create.py` first, then update the `JSON_FILE` and `SOURCE_FILE` constants to match the filename that it wrote. |
| 39 | + |
| 40 | +## A Note on Models |
| 41 | + |
| 42 | +The GPT Image models replaced DALL·E, which OpenAI [retired on May 12, 2026](https://developers.openai.com/api/docs/deprecations) along with the image variations endpoint. These scripts call `gpt-image-2.5-flare`. |
| 43 | + |
| 44 | +OpenAI retires image models on a regular schedule, so if a script starts failing with a message like `The model 'gpt-image-2.5-flare' does not exist`, then check the deprecations page and swap the model name. |
0 commit comments