Reputation: 483
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
{'error': {'code': None, 'message': 'Invalid URL (POST /v1/images/generate)', 'param': None, 'type': 'invalid_request_error'}}
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.
TypeError: 'ImagesResponse' object is not subscriptable
Upvotes: 0
Views: 2021
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:
Upvotes: 1