Generate Images With OpenAI in Python

In this world where Generative AI is getting popular, we can generate images using AI models. DALL-E by OpenAI is a powerful service that creates realistic images from text prompts, similar to how ChatGPT works with text.

In this article, we will learn how to use the DALL-E API to generate images in Python with simple code examples.

What is DALL-E from OpenAI?

DALL-E is an AI model developed by OpenAI that generates images from natural language descriptions. It uses advanced neural networks and diffusion models to understand text prompts and create corresponding visual content.

The model is based on a modified version of OpenAI GPT-3 and has been trained on millions of image-text pairs. This training allows DALL-E to understand the relationship between textual descriptions and visual concepts.

Prerequisites

Before following this tutorial, you need ?

  • OpenAI account with available API credits

  • Python 3.7.1 or higher installed

  • Basic knowledge of Python programming

  • Understanding of API usage

Setting Up Your Environment

Step 1: Get OpenAI API Key

First, create an OpenAI account and generate an API key ?

  • Login to your OpenAI account

  • Click on your profile icon in the upper right corner

  • Select "View API keys"

  • Click "Create a new secret key"

  • Copy and save the generated key securely

Step 2: Install Required Library

Check your Python version and install the OpenAI library ?

python --version

Create and activate a virtual environment ?

Windows:

python -m venv venv
.\venv\Scripts\activate

Linux/MacOS:

python -m venv venv
source venv/bin/activate

Install the OpenAI library ?

pip install openai

Step 3: Set Environment Variable

Set up your API key as an environment variable for security ?

Windows:

set OPENAI_API_KEY=your-api-key-here

Linux/MacOS:

export OPENAI_API_KEY=your-api-key-here

DALL-E Pricing

OpenAI charges based on image resolution. Here are the current prices ?

Resolution Price per Image
256×256 $0.016
512×512 $0.018
1024×1024 $0.020

Note: New OpenAI accounts receive $18 in free credits valid for the first 3 months.

Generating Images with Python

Here's a complete example that generates an image using DALL-E ?

import openai
import os

# Set your API key
openai.api_key = os.getenv("OPENAI_API_KEY")

# Define your prompt
prompt = "A futuristic city skyline at sunset with flying cars"

# Generate image
response = openai.Image.create(
    prompt=prompt,
    n=1,  # Number of images to generate
    size="512x512"  # Image resolution
)

# Get the image URL
image_url = response["data"][0]["url"]
print(f"Generated image URL: {image_url}")

Parameters Explanation

  • prompt Text description of the image you want to generate

  • n Number of images to generate (1-10)

  • size Resolution: "256x256", "512x512", or "1024x1024"

Advanced Example with Error Handling

import openai
import os
import requests
from PIL import Image
from io import BytesIO

def generate_and_save_image(prompt, filename="generated_image.png"):
    try:
        # Set API key
        openai.api_key = os.getenv("OPENAI_API_KEY")
        
        # Generate image
        response = openai.Image.create(
            prompt=prompt,
            n=1,
            size="1024x1024"
        )
        
        # Get image URL
        image_url = response["data"][0]["url"]
        
        # Download and save image
        image_response = requests.get(image_url)
        image = Image.open(BytesIO(image_response.content))
        image.save(filename)
        
        print(f"Image saved as {filename}")
        return image_url
        
    except Exception as e:
        print(f"Error generating image: {e}")
        return None

# Example usage
prompt = "A serene mountain landscape with a crystal clear lake"
url = generate_and_save_image(prompt, "mountain_lake.png")
if url:
    print(f"Image URL: {url}")

Best Practices

  • Clear prompts: Use descriptive and specific language

  • API key security: Never hardcode API keys in your source code

  • Error handling: Always implement proper error handling

  • Cost management: Monitor your API usage to control costs

Common Use Cases

  • Creating artwork for blogs and websites

  • Generating product mockups and prototypes

  • Creating educational visual content

  • Designing social media graphics

Conclusion

DALL-E provides a powerful way to generate high-quality images from text prompts using Python. With proper setup and clear prompts, you can create unique visual content for various applications. Remember to manage your API usage costs and implement proper error handling in production code.

Updated on: 2026-03-27T16:23:53+05:30

406 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements