Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Image Generation using OpenAI API

Introduction

Image generation with the OpenAI API allows you to create images from text prompts using advanced AI models. This tutorial covers how to use the image generation endpoint effectively, its parameters, and examples in JavaScript and Python.

Endpoint Overview

The image generation endpoint leverages AI to generate images based on provided text descriptions. This can be used in various applications, from art creation to generating visual content for stories and articles.

Using the Image Generation Endpoint

API Request

To generate images, send a POST request to the endpoint URL with your API key and the text prompt.

POST /v1/images/generations HTTP/1.1
Host: api.openai.com
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

{
    "prompt": "A surreal painting of a futuristic cityscape.",
    "n": 1,
    "size": "1024x1024"
}
                    

In this example, an image is generated based on the prompt: "A surreal painting of a futuristic cityscape."

API Response

The API responds with the generated images in the form of URLs or base64-encoded strings.

HTTP/1.1 200 OK
Content-Type: application/json

{
    "data": [
        {
            "url": "https://openai.com/api/images/generated/some-image.jpg"
        }
    ]
}
                    

The response includes the URL of the generated image.

Parameters

Here are some common parameters you can use with the image generation endpoint:

  • prompt: The text description for the image you want to generate.
  • n: The number of images to generate.
  • size: The size of the generated image (e.g., "256x256", "512x512", "1024x1024").

Examples in JavaScript

Here's how you can use the image generation endpoint in JavaScript:

const axios = require('axios');

const apiKey = 'YOUR_API_KEY';
const endpoint = 'https://api.openai.com/v1/images/generations';

async function generateImage(prompt) {
    try {
        const response = await axios.post(endpoint, {
            prompt: prompt,
            n: 1,
            size: '1024x1024'
        }, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            }
        });

        console.log(response.data.data[0].url);
    } catch (error) {
        console.error('Error:', error);
    }
}

generateImage('A surreal painting of a futuristic cityscape.');
                

Examples in Python

Here's how you can use the image generation endpoint in Python:

import requests
import json

api_key = 'YOUR_API_KEY'
endpoint = 'https://api.openai.com/v1/images/generations'

def generate_image(prompt):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }
    data = {
        'prompt': prompt,
        'n': 1,
        'size': '1024x1024'
    }

    response = requests.post(endpoint, headers=headers, data=json.dumps(data))
    if response.status_code == 200:
        image_url = response.json()['data'][0]['url']
        print(image_url)
    else:
        print(f"Error: {response.status_code}, {response.text}")

generate_image('A surreal painting of a futuristic cityscape.');
                

Conclusion

The image generation endpoint in the OpenAI API provides a powerful tool to create images based on text descriptions. By understanding its usage, parameters, and seeing examples in JavaScript and Python, you can integrate image generation seamlessly into various applications for generating visual content.