Learn to generate images from text prompts using OpenAI’s DALL·E API with customization options for outputs and resolution.
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.
Import packages, configure your key, and wrap the DALL·E call in a reusable function:
Copy
Ask AI
import osimport openaifrom IPython.display import Image, display# Load API key from environmentopenai.api_key = os.getenv("OPENAI_API_KEY")# Alternatively, set directly (not recommended for production)def generate_image(prompt: str, size: str = "512x512", n: int = 1, response_format: str = "url"): """ Generate `n` images for a given text prompt. Args: prompt: Text description to guide image creation. size: Resolution, choose from our supported list. n: Number of images to generate. response_format: "url" or "b64_json". Returns: A list of dicts containing the image data (URL or base64 JSON). """ response = openai.Image.create( prompt=prompt, n=n, size=size, response_format=response_format ) return response["data"]
Create a 512×512 image of a “cozy coffee-shop corner” and render it in Jupyter:
Copy
Ask AI
# Generate one imageimages = generate_image( prompt="Interior photography of a cozy corner in a coffee shop, using natural light.", size="512x512", n=1)# Display the first resultimage_url = images[0]["url"]Image(url=image_url, width=512)
Request several variations at once by increasing n and iterating over the response:
Copy
Ask AI
# Generate three variationsimages = generate_image( prompt="Interior photography of a cozy corner in a coffee shop, using natural light.", size="512x512", n=3)# Display all generated images side by sidefor img in images: display(Image(url=img["url"], width=256))