sydadder
sydadder

Reputation: 483

How to generate image from openAi using Python

Using python how can we generate and download an image using OpenAI api? Surprisingly, I've got the following code from chatgpt which should have provided me with the latest working version but it didn't

import requests
import os

# Replace 'your_api_key' with your actual OpenAI API key
api_key = 'your_api_key'

# The URL for OpenAI's image generation endpoint
url = "https://api.openai.com/v1/images/generate"

# The parameters for the image generation request
payload = {
    "prompt": "A futuristic cityscape at sunset",
    "n": 1,
    "size": "1024x1024"
}

# The headers, including the authorization with your API key
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key}"
}

# Make the POST request to OpenAI's API
response = requests.post(url, json=payload, headers=headers)

# Check if the request was successful
if response.status_code == 200:
    # Get the URL of the generated image
    image_url = response.json()['data'][0]['url']

    # Download the image
    image_response = requests.get(image_url)

    # Save the image to a file
    if image_response.status_code == 200:
        with open('generated_image.png', 'wb') as f:
            f.write(image_response.content)
        print("Image downloaded and saved as 'generated_image.png'")
    else:
        print("Failed to download the image")
else:
    print(f"Failed to generate image: {response.status_code}")
    print(response.json())

Following are few of the errors that I've encountered

  1. {'error': {'code': None, 'message': 'Invalid URL (POST /v1/images/generate)', 'param': None, 'type': 'invalid_request_error'}}

  2. You tried to access openai.Image, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

  3. TypeError: 'ImagesResponse' object is not subscriptable

Upvotes: 0

Views: 2021

Answers (1)

sydadder
sydadder

Reputation: 483

With the latest version of the OpenAI installed, following code should work:

from openai import OpenAI
import requests

api_key = 'YOUR-API-KEY-AVAILABLE-ON-Monthly-subscription'
user_prompt =  prompt = "image for landing page on website of an assignment and dissertation writing service"

client = OpenAI(
    # This is the default and can be omitted
    api_key=api_key,
)

response = client.images.generate(prompt=prompt)

# Extract the URL of the generated image
image_url = response.data[0].url
image_response = requests.get(image_url)

# Save the image to a file
if image_response.status_code == 200:
    with open('generated_image.png', 'wb') as f:
        f.write(image_response.content)
    print("Image downloaded and saved as 'generated_image.png'")
else:
    print("Failed to download the image")

Explanation:

  1. Install and import necessary libraries: Ensure openai and requests libraries are installed and imported.
  2. Set API key: Set your OpenAI API key for authentication.
  3. Generate an image: Use the client.images.generate method to generate an image based on the provided prompt.
  4. Extract the URL: Access the URL of the generated image from the response.
  5. Download and save the image: Use the requests library to download the image and save it locally.

Upvotes: 1

Related Questions