Using OpenAi image generation api to generate images from given prompt.

krishankant singhal
2 min readMar 10, 2024

you want to write a program which take prompt as an input and generate the images as output, we can use openai image generation api using various openai model like dall-e-3,dall-e-2 etc. in this tutorial we will see how we can use dall-e-3 model to generate our image.

import streamlit as st
from openai import OpenAI
import os

# Replace with your OpenAI API key
os.environ['OPENAI_API_KEY'] = 'YOUR_OPENAI_API_KEY'

# Initialize OpenAI client
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
)

def generate_images(prompt, num_images=1):
"""
Generates images using the OpenAI Image Generation API.

Args:
prompt: The text prompt describing the desired images.
num_images: The number of images to generate (default: 1).

Returns:
A list of image URLs.
"""
response = client.images.generate(
model="dall-e-3",
prompt=prompt,
n=num_images,
size="1024x1024", # You can adjust the image size here
)
return [image.url for image in response.data]

st.title("OpenAI Image Generation")

# Text input for user prompt
user_prompt = st.text_input("Enter your prompt:")

# Number input for image count (optional)
num_images = st.number_input("Number of images to generate", min_value=1, max_value=4, value=1)

# Button to trigger image generation
if st.button("Generate Images"):
with st.spinner("Generating images..."):
image_urls = generate_images(user_prompt, num_images)

# Display generated images
for i, url in enumerate(image_urls)…

--

--

krishankant singhal

Angular,Vuejs,Android,Java,Git developer. i am nerd who want to learn new technologies, goes in depth.