Predictive Hacks

How to Generate and Save Images with DALL-E 2 using OpenAI

To generate images with OpenAI, you can use OpenAI’s DALL-E 2 API. Here’s an example code snippet that shows how to generate and save images an image with DALL-E 2 using OpenAI’s API:

import openai
import os
import urllib.request
openai.api_key = os.getenv('OpenAI')

# Let's ask for 3 images of a mathematician that writes on a blackboard

response = openai.Image.create(
            prompt = 'A mathematician is writing equations on the blackboard',
            size = '512x512')

# save the images locally

if "data" in response:
    for key, obj in enumerate(response["data"]):
        filename ='my_image_'+str(key)+".jpg"
        urllib.request.urlretrieve(obj['url'], filename)
    print('Images have been downloaded and saved locally')
    print("Failed to generate image")
Images have been downloaded and saved locally

As you can see, we generated and downloaded the 3 images locally!

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore


Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.


Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s