[Python] How to generate image from OpenAI using Python

Discussão em 'Python' iniciado por Stack, Junho 12, 2025.

  1. Stack

    Stack Membro Participativo

    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

    Continue reading...

Compartilhe esta Página