Generate Images With OpenAI in Python
Last Updated :
23 Jul, 2025
We are currently living in the age of AI. Images to automate processes including image generation for logos, advertisements, stock images, etc. So here we will use OpenAI to generate Images with Python [ChatGPT API]. There are numerous uses of the DALL - E model and today we will be discussing how one can use its Python ChatGPT API [OpenAI API] to generate new images and edit existing images. But, before moving ahead let's know a little about what DALL E is.
Create AI Image Using PythonCreate AI Image Using Python
DALL - E is developed by OpenAI. It is based on a modified version of the GPT-3 model that allows the AI model to generate images from textual or image input. DALL - E is trained on 3.5 billion parameters which allows it to perform a wide range of tasks on images seamlessly. DALL - E has many use cases like social media content creation, logo creation, editing images, advertisement generation, and many others, thus making it a valuable tool in today's time.
Generate Images With OpenAI in Python
Here we are going to see the steps to use DALL - E API in Python. Using DALL - E API we are able to generate and edit images using Python code.
Step 1: Log in to your OpenAI account after creating one.
Step 2: As shown in the figure below, after logging in, select Personal from the top-right menu, and then select "View API keys".
Step 3: After completing step 2, a page containing API keys is displayed, and the button "Create new secret key" is visible. A secret key is generated when you click on that, copy it and save it somewhere else because it will be needed in further steps.
Step 4: Now launch any text editor or online notebook such as Google Colab or Jupyter Notebook. Here, we're using a Google Colab notebook to install the Open AI library in Python with the command listed below.
pip install -q openai
Step 5: Import the openai library, and then do as follows. Store the created key in the below-mentioned variable.
python
# importing openai module
import openai
# assigning API KEY to the variable
openai.api_key = 'API_KEY'
Step 6: Import the requests library and Image module from PIL library.
Python
# importing other libraries
import requests
from PIL import Image
Step 7: Now we define a function to generate an Image using the "create" endpoint of DALL E API.
Python
# function for text-to-image generation
# using create endpoint of DALL-E API
# function takes in a string argument
def generate(text):
res = openai.Image.create(
# text describing the generated image
prompt=text,
# number of images to generate
n=1,
# size of each generated image
size="256x256",
)
# returning the URL of one image as
# we are generating only one image
return res["data"][0]["url"]
The above function takes a string as an argument and passes it to the API endpoint. The other are parameters used are n = "number of images generated using that prompt" and size = "size of the image generated". The API can give generate the image in either Base64 format or URL. We return the URL of the generated image as the output.
Note: The size of the generated images must be one of 256x256, 512x512, or 1024x1024.
Step 8: Now we generate an Image using the Text Prompt.
Python
# prompt describing the desired image
text = "batman art in red and blue color"
# calling the custom function "generate"
# saving the output in "url1"
url1 = generate(text)
# using requests library to get the image in bytes
response = requests.get(url1)
# using the Image module from PIL library to view the image
Image.open(response.raw)
Output:
batman art in red and blue colorHow to Generate Variations of an Image?
Here we are going to use the same image generated above by DALL E and generate its variations.
Since DALL E only accepts square PNG images with sizes less than 4 MB and in RGBA format, we save our image with extension png and in RGBA format using the following code.
Python
response = requests.get(url1)
# saving the image in PNG format
with open("img.png", "wb") as f:
f.write(response.content)
# opening the saved image and converting it into "RGBA" format
# converted image is saved in result
result = Image.open('img.png').convert('RGBA')
# saving the new image in PNG format
result.save('img_rgba.png','PNG')
To generate variations of an existing Image we use the "create_edit" endpoint of the DALL-E API.
Python
# editing image using create_edit endpoint of DALL-E API
response = openai.Image.create_edit(
# opening original image in read mode
image=open("/content/img_rgba.png", "rb"),
# opening mask image in read mode
mask=open("/content/mask.png", "rb"),
# propmt describing the desired image
prompt="gotham city skyline behind batman",
# number of images to be generated
n=3,
# size of each generated image
size="256x256"
)
# saving the URLs of all image in new variable "res"
res = response['data']
# loop to save and display images
for i in range(len(res)):
# saving URL of image in res
image_url = res[i]['url']
# extracting image from URL in bytes form
response = requests.get(image_url, stream=True)
# opening the image
k = Image.open(response.raw)
# displaying the image
k.show()
# saving the image
with open(f"img_variant_{i}.png", "wb") as f:
f.write(response.content)
Output:
How to Edit Images using a Mask Image with DALL E API?
In this section, a mask will be uploaded and a text prompt will be supplied in order to change an image. Where the image should be altered is indicated by the transparent portions of the mask, and the prompt should describe the entire new image rather than just the area that was erased.
Make sure your image and mask are of the same size (square PNG) and less than 4MB in size before passing them as arguments to API. We will be using the following images.
input imageAlso, write a prompt such that it describes the full new image not just the transparent area that needs to be replaced.Use the following lines of code to edit the image.
Python
# using create_edit endpoint of the DALL - E API
response = openai.Image.create_edit(
# opening original image in read mode
image=open("img_rgba.png", "rb"),
# opening mask image in read mode
mask=open("mask.png", "rb"),
# text prompt describing the new image
prompt="gotham city skyline behind batman",
# number of images to be generated
n=1,
#size of each image generated in pixels
size="256x256"
)
# saving the URLs of all image in new variable "res"
res = response['data']
# loop to save and display images
for i in range(len(res)):
# saving URL of image in res
image_url = res[i]['url']
# extracting image from URL in bytes form
response = requests.get(image_url, stream=True)
# opening the image
k = Image.open(response.raw)
# displaying the image
k.show()
# saving the image
with open(f"img_mask_edit_{i}.png", "wb") as f:
f.write(response.content)
Output:

It is not necessary for the non-transparent portions of the mask to match the original image, as in the example above, because they are not used when creating the output.
Conclusion
We covered several ways in the whole article for generating new images and editing existing images using DALL - E API using Python which would help you in achieving your desired outputs. There are numerous use cases of DALL - E like social media content generation, logo creation, or generating stock photos, etc.
To learn more about Chat GPT, you can refer to:
Generate Images With OpenAI in Python
Similar Reads
Data Science Tutorial Data Science is a field that combines statistics, machine learning and data visualization to extract meaningful insights from vast amounts of raw data and make informed decisions, helping businesses and industries to optimize their operations and predict future trends.This Data Science tutorial offe
3 min read
Introduction to Machine Learning
What is Data Science?Data science is the study of data that helps us derive useful insight for business decision making. Data Science is all about using tools, techniques, and creativity to uncover insights hidden within data. It combines math, computer science, and domain expertise to tackle real-world challenges in a
8 min read
Top 25 Python Libraries for Data Science in 2025Data Science continues to evolve with new challenges and innovations. In 2025, the role of Python has only grown stronger as it powers data science workflows. It will remain the dominant programming language in the field of data science. Its extensive ecosystem of libraries makes data manipulation,
10 min read
Difference between Structured, Semi-structured and Unstructured dataBig Data includes huge volume, high velocity, and extensible variety of data. There are 3 types: Structured data, Semi-structured data, and Unstructured data. Structured data - Structured data is data whose elements are addressable for effective analysis. It has been organized into a formatted repos
2 min read
Types of Machine LearningMachine learning is the branch of Artificial Intelligence that focuses on developing models and algorithms that let computers learn from data and improve from previous experience without being explicitly programmed for every task.In simple words, ML teaches the systems to think and understand like h
13 min read
What's Data Science Pipeline?Data Science is a field that focuses on extracting knowledge from data sets that are huge in amount. It includes preparing data, doing analysis and presenting findings to make informed decisions in an organization. A pipeline in data science is a set of actions which changes the raw data from variou
3 min read
Applications of Data ScienceData Science is the deep study of a large quantity of data, which involves extracting some meaning from the raw, structured, and unstructured data. Extracting meaningful data from large amounts usesalgorithms processing of data and this processing can be done using statistical techniques and algorit
6 min read
Python for Machine Learning
Learn Data Science Tutorial With PythonData Science has become one of the fastest-growing fields in recent years, helping organizations to make informed decisions, solve problems and understand human behavior. As the volume of data grows so does the demand for skilled data scientists. The most common languages used for data science are P
3 min read
Pandas TutorialPandas (stands for Python Data Analysis) is an open-source software library designed for data manipulation and analysis. Revolves around two primary Data structures: Series (1D) and DataFrame (2D)Built on top of NumPy, efficiently manages large datasets, offering tools for data cleaning, transformat
6 min read
NumPy Tutorial - Python LibraryNumPy is a core Python library for numerical computing, built for handling large arrays and matrices efficiently.ndarray object â Stores homogeneous data in n-dimensional arrays for fast processing.Vectorized operations â Perform element-wise calculations without explicit loops.Broadcasting â Apply
3 min read
Scikit Learn TutorialScikit-learn (also known as sklearn) is a widely-used open-source Python library for machine learning. It builds on other scientific libraries like NumPy, SciPy and Matplotlib to provide efficient tools for predictive data analysis and data mining.It offers a consistent and simple interface for a ra
3 min read
ML | Data Preprocessing in PythonData preprocessing is a important step in the data science transforming raw data into a clean structured format for analysis. It involves tasks like handling missing values, normalizing data and encoding variables. Mastering preprocessing in Python ensures reliable insights for accurate predictions
6 min read
EDA - Exploratory Data Analysis in PythonExploratory Data Analysis (EDA) is a important step in data analysis which focuses on understanding patterns, trends and relationships through statistical tools and visualizations. Python offers various libraries like pandas, numPy, matplotlib, seaborn and plotly which enables effective exploration
6 min read
Introduction to Statistics
Statistics For Data ScienceStatistics is like a toolkit we use to understand and make sense of information. It helps us collect, organize, analyze and interpret data to find patterns, trends and relationships in the world around us.From analyzing scientific experiments to making informed business decisions, statistics plays a
12 min read
Descriptive StatisticStatistics is the foundation of data science. Descriptive statistics are simple tools that help us understand and summarize data. They show the basic features of a dataset, like the average, highest and lowest values and how spread out the numbers are. It's the first step in making sense of informat
5 min read
What is Inferential Statistics?Inferential statistics is an important tool that allows us to make predictions and conclusions about a population based on sample data. Unlike descriptive statistics, which only summarize data, inferential statistics let us test hypotheses, make estimates, and measure the uncertainty about our predi
7 min read
Bayes' TheoremBayes' Theorem is a mathematical formula used to determine the conditional probability of an event based on prior knowledge and new evidence. It adjusts probabilities when new information comes in and helps make better decisions in uncertain situations.Bayes' Theorem helps us update probabilities ba
13 min read
Probability Data Distributions in Data ScienceUnderstanding how data behaves is one of the first steps in data science. Before we dive into building models or running analysis, we need to understand how the values in our dataset are spread out and thatâs where probability distributions come in.Let us start with a simple example: If you roll a f
8 min read
Parametric Methods in StatisticsParametric statistical methods are those that make assumptions regarding the distribution of the population. These methods presume that the data have a known distribution (e.g., normal, binomial, Poisson) and rely on parameters (e.g., mean and variance) to define the data.Key AssumptionsParametric t
6 min read
Non-Parametric TestsNon-parametric tests are applied in hypothesis testing when the data does not satisfy the assumptions necessary for parametric tests, such as normality or equal variances. These tests are especially helpful for analyzing ordinal data, small sample sizes, or data with outliers.Common Non-Parametric T
5 min read
Hypothesis TestingHypothesis testing compares two opposite ideas about a group of people or things and uses data from a small part of that group (a sample) to decide which idea is more likely true. We collect and study the sample data to check if the claim is correct.Hypothesis TestingFor example, if a company says i
9 min read
ANOVA for Data Science and Data AnalyticsANOVA is useful when we need to compare more than two groups and determine whether their means are significantly different. Suppose you're trying to understand which ingredients in a recipe affect its taste. Some ingredients, like spices might have a strong influence while others like a pinch of sal
9 min read
Bayesian Statistics & ProbabilityBayesian statistics sees unknown values as things that can change and updates what we believe about them whenever we get new information. It uses Bayesâ Theorem to combine what we already know with new data to get better estimates. In simple words, it means changing our initial guesses based on the
6 min read
Feature Engineering
Model Evaluation and Tuning
Data Science Practice