AI & Automation

Using OpenAI DALL-E 3 to Generate and Save Images Locally

·4 min read
Using OpenAI DALL-E 3 to Generate and Save Images Locally

Using OpenAI DALL-E 3 to Generate and Save Images Locally

In this tutorial, we'll explore how to use OpenAI's DALL-E 3 API to generate images based on text prompts and save them locally. This guide will walk you through setting up your environment, writing the code, and running the tool.

Prerequisites

Before you begin, ensure you have the following:

  • A valid OpenAI API key
  • Python installed on your system
  • Basic knowledge of Python programming

Setting Up Your Environment

First, install the necessary Python packages:

pip install openai requests python-dotenv

Creating the Script

Let's create a Python script that will:

  1. Connect to the OpenAI API
  2. Send a text prompt to DALL-E 3
  3. Download and save the generated image locally

Create a new file called dalle_image_generator.py with the following code:

import os
import requests
import time
from datetime import datetime
from openai import OpenAI
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Get API key from environment variable
api_key = os.getenv("OPENAI_API_KEY")

# Initialize the OpenAI client
client = OpenAI(api_key=api_key)

def generate_image(prompt, size="1024x1024", quality="standard", n=1):
    """
    Generate an image using DALL-E 3

    Parameters:
    - prompt: Text description of the image to generate
    - size: Image size (1024x1024, 1792x1024, or 1024x1792)
    - quality: Image quality (standard or hd)
    - n: Number of images to generate

    Returns:
    - List of image URLs
    """
    try:
        response = client.images.generate(
            model="dall-e-3",
            prompt=prompt,
            size=size,
            quality=quality,
            n=n
        )

        # Extract image URLs from the response
        image_urls = [image.url for image in response.data]
        return image_urls

    except Exception as e:
        print(f"Error generating image: {e}")
        return None

def download_image(url, output_dir="generated_images"):
    """
    Download an image from a URL and save it locally

    Parameters:
    - url: URL of the image to download
    - output_dir: Directory to save the image

    Returns:
    - Path to the saved image
    """
    try:
        # Create output directory if it doesn't exist
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        # Generate a filename based on timestamp
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"{output_dir}/dalle3_image_{timestamp}.png"

        # Download the image
        response = requests.get(url)

        # Save the image to a file
        with open(filename, "wb") as f:
            f.write(response.content)

        print(f"Image saved to {filename}")
        return filename

    except Exception as e:
        print(f"Error downloading image: {e}")
        return None

def main():
    # Get user input for the image prompt
    prompt = input("Enter a description for the image you want to generate: ")

    # Generate the image
    print("Generating image...")
    image_urls = generate_image(prompt)

    if image_urls:
        # Download each generated image
        for url in image_urls:
            download_image(url)
    else:
        print("Failed to generate image.")

if __name__ == "__main__":
    main()

Setting Up Environment Variables

Create a .env file in the same directory as your script to store your OpenAI API key:

OPENAI_API_KEY=your_api_key_here

Replace your_api_key_here with your actual OpenAI API key.

Running the Tool

To run the tool, execute the Python script:

python dalle_image_generator.py

You'll be prompted to enter a description for the image you want to generate. After entering your prompt, the script will:

  1. Send the prompt to DALL-E 3
  2. Generate the image
  3. Download the image and save it to the generated_images folder

Customizing the Image Generation

You can customize the image generation by modifying the parameters in the generate_image function call:

  • Size: Choose between "1024x1024" (square), "1792x1024" (landscape), or "1024x1792" (portrait)
  • Quality: Choose between "standard" or "hd" (higher quality but costs more)
  • Number of images: Specify how many variations to generate

For example, to generate a high-quality landscape image:

image_urls = generate_image(
    prompt=prompt,
    size="1792x1024",
    quality="hd",
    n=1
)

Error Handling and Rate Limits

The script includes basic error handling, but be aware that OpenAI's API has rate limits. If you're generating many images, you might need to implement additional error handling and rate limiting in your code.

Conclusion

You now have a simple but powerful tool for generating images with DALL-E 3 and saving them locally. This can be useful for creative projects, content creation, or any application where you need AI-generated images.

Some potential enhancements you might consider:

  • Adding a web interface
  • Implementing batch processing for multiple prompts
  • Saving the prompts alongside the images for reference
  • Adding options to modify the image after generation

Remember that when using DALL-E 3, you should follow OpenAI's usage policies and be mindful of the content you generate.

Happy image generating!