Skip to main content

Generate an Image

Create images from text prompts using the images.generate method.
require "openai"

client = OpenAI::Client.new

prompt = "An astronaut lounging in a tropical resort in space, pixel art"

# Generate an image based on the prompt
response = client.images.generate(prompt: prompt)

# Prints response containing a URL link to image
pp(response)

Generate with Parameters

Customize image generation with model, size, and quantity parameters.
response = client.images.generate(
  model: "gpt-image-1",
  prompt: "A cute baby sea otter",
  n: 1,
  size: "1024x1024"
)

pp(response)

Edit an Image

Edit existing images by providing an image file and a prompt describing the desired changes.
require "pathname"

image = OpenAI::FilePart.new(Pathname('dog.jpg'), content_type: 'image/jpeg')

edited = client.images.edit(
  prompt: "make this image look like a painting",
  model: "gpt-image-1",
  size: '1024x1024',
  image: image
)

puts(edited.data.first)
The OpenAI::FilePart class allows you to control the filename and content type when uploading images.

Stream Image Generation

Receive partial images during generation for a progressive loading experience.
require "base64"

stream = client.images.generate_stream_raw(
  model: "gpt-image-1",
  prompt: "A cute baby sea otter",
  n: 1,
  size: "1024x1024",
  partial_images: 3
)

stream.each do |event|
  case event
  when OpenAI::Models::ImageGenPartialImageEvent
    puts("Partial image #{event.partial_image_index + 1}/3 received")
    puts("Size: #{event.b64_json.length} characters (base64)")

    # Save partial image to file
    filename = "partial_#{event.partial_image_index + 1}.png"
    image_data = Base64.decode64(event.b64_json)
    File.write(filename, image_data)
    puts("Saved to: #{File.expand_path(filename)}")

  when OpenAI::Models::ImageGenCompletedEvent
    puts("\n✅ Final image completed!")
    puts("Size: #{event.b64_json.length} characters (base64)")

    # Save final image to file
    filename = "final_image.png"
    image_data = Base64.decode64(event.b64_json)
    File.write(filename, image_data)
    puts("Saved to: #{File.expand_path(filename)}")
  end
end
The streaming API provides both partial images during generation and the final completed image, allowing you to show progressive updates to users.

Image Response Format

Images can be returned as URLs or base64-encoded JSON. By default, the API returns URLs, but you can request base64 encoding for direct file operations.
# Request base64-encoded response
response = client.images.generate(
  prompt: "A sunset over mountains",
  response_format: "b64_json"
)

# Decode and save the image
image_data = Base64.decode64(response.data.first.b64_json)
File.write("sunset.png", image_data)

Build docs developers (and LLMs) love