Skip to main content
Learn how to generate stunning images from text prompts using the OpenAI DALL·E API. You can customize the prompt, choose the number of outputs, and select the resolution that best fits your application.

Table of Contents

  1. Prerequisites
  2. Setup and Helper Function
  3. Supported Image Sizes
  4. Generate and Display a Single Image
  5. Generate Multiple Images
  6. Base64-Encoded Output
  7. Integrating with GPT Models
  8. References

Prerequisites

  • Python 3.7+
  • An OpenAI API key
  • openai Python package
Install the SDK with:
Store your API key in an environment variable for security:

Setup and Helper Function

Import packages, configure your key, and wrap the DALL·E call in a reusable function:

Supported Image Sizes

Choose the resolution that matches your use case:

Generate and Display a Single Image

Create a 512×512 image of a “cozy coffee-shop corner” and render it in Jupyter:
Each execution produces a new, unique image.

Generate Multiple Images

Request several variations at once by increasing n and iterating over the response:

Base64-Encoded Output

If you prefer embedding images directly (e.g., in HTML or JSON), request b64_json:
Large base64 payloads can impact performance. Use b64_json sparingly.

Integrating with GPT Models

You can automate end-to-end content creation by combining DALL·E with GPT:
  1. Text-to-Image Workflow
    • Use GPT-3.5 Turbo to draft descriptive prompts.
    • Feed them into DALL·E for image generation.
  2. Prompt Engineering
    • Send long-form descriptions to GPT-4 to refine or expand for DALL·E.
    • Obtain optimized prompts that yield better visual results.
This approach can power dynamic blog posts, marketing assets, or social media content.

References

Watch Video

Practice Lab