Python OpenAI Generate Image with DALLΒ·E

To generate an image, you need to create an account and API key if you haven’t already. You can learn more about this in my tutorial here: πŸ‘‡

βœ… Recommended: OpenAI API Getting Started

Do you have an API key? Great!

To generate an image with DALLΒ·E copy&paste the following code and replace your API key and the string description of the image to be generated (prompt)

import os
import openai

# Your API Key Here: πŸ‘‡
openai.api_key = 'sk-XXXXXXXXXXXXXXXXXXXXXXXXXXX'

# Your Image Prompt Here: πŸ‘‡
prompt = "An oil painting of a dancing robot in the style of Monet"

response = openai.Image.create(
    prompt=prompt,
    n=1,
    size="256x256",
)

print(response["data"][0]["url"])

The output is a URL from where you can download the image:

https://oaidalleapiprodscus.blob.core.windows.net/private/org-CR1YqwB9GAtSsAKHpN1935Dy/user-57ZUj7285WTxwzVJdiweq6JS/img-n9aRtAjhyJMeOzZTXztvkGGD.png?st=2023-04-25T07%3A19%3A14Z&se=2023-04-25T09%3A19%3A14Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-04-25T08%3A17%3A09Z&ske=2023-04-26T08%3A17%3A09Z&sks=b&skv=2021-08-06&sig=57InZSNLylU1peJpPN8yynKvbiKBaLqhVn3l5c9oOSk%3D

You can change the size, e.g., to 1000×1000 pixels — but it’ll cost you more and takes longer:

# ...

response = openai.Image.create(
    prompt=prompt,
    n=1,
    size="1024x1024",
)

# ...

Here’s the pricing table by the way from the official API page:

ResolutionPrice
1024Γ—1024$0.020 / image
512Γ—512$0.018 / image
256Γ—256$0.016 / image

Yeah, this article just cost me $0.054. 😱

πŸš€ Recommended: Best 35 Helpful ChatGPT Prompts for Coders (2023)