SPB Git

Repository Public

image-generation.md 109.2 KB 3,622 lines markdown

1# Image generation23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45## Overview67The API lets you generate and edit images from text prompts using `gpt-image-2.5-sunburst` and `gpt-image-2.5-flare`. Choose Sunburst for workflows where editing precision matters most, and Flare for fast, high-quality everyday image generation. You can access image generation capabilities through two APIs:89### Image API1011The [Image API](https://developers.openai.com/api/reference/resources/images) provides two endpoints, each with distinct capabilities:1213- **Generations**: [Generate images](#generate-images) from scratch based on a text prompt14- **Edits**: [Modify existing images](#edit-images) using a new prompt, either partially or entirely1516### Responses API1718The [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-tools) allows you to generate images as part of conversations or multi-step flows. It supports image generation as a [built-in tool](https://developers.openai.com/api/docs/guides/tools?api-mode=responses), and accepts image inputs and outputs within context.1920Compared to the Image API, it adds:2122- **Multi-turn editing**: Iteratively make high fidelity edits to images with prompting23- **Flexible inputs**: Accept image [File](https://developers.openai.com/api/reference/resources/files) IDs as input images, not just bytes2425For mainline models that can call the image generation tool, refer to [supported models](#supported-models).2627### Choosing the right API2829- If you only need to generate or edit a single image from one prompt, the Image API is your best choice.30- If you want to build conversational, editable image experiences with GPT Image, go with the Responses API.3132With the Image API, set `model` to `gpt-image-2.5-sunburst` or `gpt-image-2.5-flare` directly. With the Responses API, select a supported mainline model at the top level and specify `gpt-image-2.5-sunburst` or `gpt-image-2.5-flare` in the image generation tool's `model` field.3334Both APIs let you [customize output](#customize-image-output) by adjusting quality, size, format, and compression.3536To ensure these models are used responsibly, you may need to complete the [API37  Organization38  Verification](https://help.openai.com/en/articles/10910291-api-organization-verification)39  from your [developer40  console](https://platform.openai.com/settings/organization/general) before41  using GPT Image models.4243<div44  className="not-prose"45  style={{ float: "right", margin: "10px 0 10px 10px" }}46>47  <img src="https://developers.openai.com/images/image-25-article/mug.png"48    alt="A beige coffee mug on a wooden table"49    style={{ height: "180px", width: "auto", borderRadius: "8px" }}50  />51525354## Generate Images5556You can use the [image generation endpoint](https://developers.openai.com/api/reference/resources/images) to create images based on text prompts, or the [image generation tool](https://developers.openai.com/api/docs/guides/tools?api-mode=responses) in the Responses API to generate images as part of a conversation.5758To learn more about customizing the output (size, quality, format, compression), refer to the [customize image output](#customize-image-output) section below.5960You can set the `n` parameter to generate multiple images at once in a single request (by default, the API returns a single image).61626364Image API6566    Generate an image6768```javascript69import OpenAI from "openai";70import fs from "fs";71const openai = new OpenAI();7273const prompt = `74A children's book drawing of a veterinarian using a stethoscope to75listen to the heartbeat of a baby otter.76`;7778const result = await openai.images.generate({79  model: "gpt-image-2.5-sunburst",80  prompt,81});8283// Save the image to a file84const image_base64 = result.data[0].b64_json;85const image_bytes = Buffer.from(image_base64, "base64");86fs.writeFileSync("otter.png", image_bytes);87```8889```python90from openai import OpenAI91import base649293client = OpenAI()9495prompt = """96A children's book drawing of a veterinarian using a stethoscope to97listen to the heartbeat of a baby otter.98"""99100result = client.images.generate(model="gpt-image-2.5-sunburst", prompt=prompt)101102image_base64 = result.data[0].b64_json103image_bytes = base64.b64decode(image_base64)104105# Save the image to a file106with open("otter.png", "wb") as f:107    f.write(image_bytes)108```109110```go111package main112113import (114	"context"115	"encoding/base64"116	"os"117118	"github.com/openai/openai-go/v3"119)120121func main() {122	client := openai.NewClient()123	result, err := client.Images.Generate(context.Background(), openai.ImageGenerateParams{124		Model: openai.ImageModel("gpt-image-2.5-sunburst"),125		Prompt: "A children's book drawing of a veterinarian using a stethoscope to " +126			"listen to the heartbeat of a baby otter.",127	})128	if err != nil {129		panic(err)130	}131	image, err := base64.StdEncoding.DecodeString(result.Data[0].B64JSON)132	if err != nil {133		panic(err)134	}135	if err := os.WriteFile("otter.png", image, 0o600); err != nil {136		panic(err)137	}138}139```140141```java142import com.openai.client.OpenAIClient;143import com.openai.client.okhttp.OpenAIOkHttpClient;144import com.openai.models.images.ImageGenerateParams;145import java.io.IOException;146import java.nio.file.Files;147import java.nio.file.Path;148import java.util.Base64;149150var images =151    client152        .images()153        .generate(154            ImageGenerateParams.builder()155                .model("gpt-image-2.5-sunburst")156                .prompt("A watercolor robot reading in a library")157                .build());158159Files.write(160    Path.of("generated-image.png"),161    Base64.getDecoder().decode(images.data().orElseThrow().get(0).b64Json().orElseThrow()));162```163164```csharp165using OpenAI.Images;166167string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;168string model = "gpt-image-2.5-sunburst";169ImageClient client = new(model, key);170171GeneratedImage image = await client.GenerateImageAsync(172    "A children's book drawing of a veterinarian using a stethoscope to "173        + "listen to the heartbeat of a baby otter."174);175176await File.WriteAllBytesAsync("otter.png", image.ImageBytes.ToArray());177```178179```ruby180require "base64"181require "openai"182183client = OpenAI::Client.new184result = client.images.generate(185  model: "gpt-image-2.5-sunburst",186  prompt: "A watercolor robot reading in a library"187)188generated_image = result.data&.first or raise "No image returned"189File.binwrite(190  "generated-image.png",191  Base64.strict_decode64(generated_image.b64_json)192)193```194195```bash196curl -X POST "https://api.openai.com/v1/images/generations" \197    -H "Authorization: Bearer $OPENAI_API_KEY" \198    -H "Content-type: application/json" \199    -d '{200        "model": "gpt-image-2.5-sunburst",201        "prompt": "A children'\''s book drawing of a veterinarian using a stethoscope to listen to the heartbeat of a baby otter."202    }' | jq -r '.data[0].b64_json' | base64 --decode > otter.png203```204205```bash206openai images generate \207  --model gpt-image-2.5-sunburst \208  --prompt "A children's book drawing of a veterinarian using a stethoscope to listen to the heartbeat of a baby otter." \209  --raw-output \210  --transform 'data.0.b64_json' | base64 --decode > otter.png211```212213  214215  216217    218Responses API219220    Generate an image221222```javascript223import OpenAI from "openai";224const openai = new OpenAI();225226const response = await openai.responses.create({227  model: "gpt-6-astra",228  input:229    "Generate an image of gray tabby cat hugging an otter with an orange scarf",230  tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],231});232233// Save the image to a file234const imageData = response.output235  .filter((output) => output.type === "image_generation_call")236  .map((output) => output.result);237238if (imageData.length > 0) {239  const imageBase64 = imageData[0];240  const fs = await import("fs");241  fs.writeFileSync("otter.png", Buffer.from(imageBase64, "base64"));242}243```244245```python246from openai import OpenAI247import base64248249client = OpenAI()250251response = client.responses.create(252    model="gpt-6-astra",253    input="Generate an image of gray tabby cat hugging an otter with an orange scarf",254    tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],255)256257# Save the image to a file258image_data = [259    output.result260    for output in response.output261    if output.type == "image_generation_call"262]263264if image_data:265    image_base64 = image_data[0]266    with open("otter.png", "wb") as f:267        f.write(base64.b64decode(image_base64))268```269270```go271package main272273import (274	"context"275	"encoding/base64"276	"os"277278	"github.com/openai/openai-go/v3"279	"github.com/openai/openai-go/v3/responses"280)281282func main() {283	client := openai.NewClient()284	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{285		Model: "gpt-6-astra",286		Input: responses.ResponseNewParamsInputUnion{287			OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),288		},289		Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},290	})291	if err != nil {292		panic(err)293	}294	saveFirstGeneratedImage(response, "otter.png")295}296297func saveFirstGeneratedImage(response *responses.Response, filename string) {298	for _, output := range response.Output {299		if output.Type != "image_generation_call" {300			continue301		}302		image, err := base64.StdEncoding.DecodeString(output.AsImageGenerationCall().Result)303		if err != nil {304			panic(err)305		}306		if err := os.WriteFile(filename, image, 0o600); err != nil {307			panic(err)308		}309		return310	}311	panic("response did not include an image generation call")312}313```314315```java316import com.openai.client.OpenAIClient;317import com.openai.client.okhttp.OpenAIOkHttpClient;318import com.openai.models.responses.ResponseCreateParams;319import com.openai.models.responses.Tool;320import java.nio.file.Files;321import java.nio.file.Path;322import java.util.Base64;323324ResponseCreateParams params =325    ResponseCreateParams.builder()326        .model("gpt-6-astra")327        .input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")328        .addTool(Tool.ImageGeneration.builder().build())329        .build();330331var image =332    client.responses().create(params).output().stream()333        .flatMap(item -> item.imageGenerationCall().stream())334        .findFirst()335        .orElseThrow(() -> new IllegalStateException("No image generation call returned"));336String encoded =337    image.result().orElseThrow(() -> new IllegalStateException("No image returned"));338Files.write(Path.of("otter.png"), Base64.getDecoder().decode(encoded));339```340341```csharp342using OpenAI.Responses;343#pragma warning disable OPENAI001344345string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;346ResponsesClient client = new(key);347348CreateResponseOptions options = new() { Model = "gpt-6-astra" };349options.InputItems.Add(350    ResponseItem.CreateUserMessageItem(351        "Generate an image of a gray tabby cat hugging an otter with an orange scarf."352    )353);354options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));355356ResponseResult response = await client.CreateResponseAsync(options);357ImageGenerationCallResponseItem image = response358    .OutputItems.OfType<ImageGenerationCallResponseItem>()359    .FirstOrDefault()360    ?? throw new InvalidOperationException("No generated image was returned.");361await File.WriteAllBytesAsync("otter.png", image.ImageResultBytes.ToArray());362```363364```ruby365require "base64"366require "openai"367368client = OpenAI::Client.new369response = client.responses.create(370  model: "gpt-6-astra",371  input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",372  tools: [373    {374      type: :image_generation,375      model: "gpt-image-2.5-sunburst"376    }377  ]378)379380image_call = response.output.find do |item|381  item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)382end383unless image_call.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)384  raise "No image generation call returned"385end386387encoded_image = image_call.result or raise "No image returned"388File.binwrite("otter.png", Base64.strict_decode64(encoded_image))389```390391392393### Multi-turn image generation394395With the Responses API, you can build multi-turn conversations involving image generation either by providing image generation calls outputs within context (you can also just use the image ID), or by using the [`previous_response_id` parameter](https://developers.openai.com/api/docs/guides/conversation-state?api-mode=responses#openai-apis-for-conversation-state).396This lets you iterate on images across multiple turns—refining prompts, applying new instructions, and evolving the visual output as the conversation progresses.397398With the Responses API image generation tool, supported tool models can choose whether to generate a new image or edit one already in the conversation. The optional `action` parameter controls this behavior: keep `action: "auto"` to let the model decide, set `action: "generate"` to always create a new image, or set `action: "edit"` to force editing when an image is in context.399400Force image creation with action401402```javascript403import OpenAI from "openai";404const openai = new OpenAI();405406const response = await openai.responses.create({407  model: "gpt-6-astra",408  input:409    "Generate an image of gray tabby cat hugging an otter with an orange scarf",410  tools: [411    { type: "image_generation", model: "gpt-image-2.5-sunburst", action: "generate" },412  ],413});414415// Save the image to a file416const imageData = response.output417  .filter((output) => output.type === "image_generation_call")418  .map((output) => output.result);419420if (imageData.length > 0) {421  const imageBase64 = imageData[0];422  const fs = await import("fs");423  fs.writeFileSync("otter.png", Buffer.from(imageBase64, "base64"));424}425```426427```python428from openai import OpenAI429import base64430431client = OpenAI()432433response = client.responses.create(434    model="gpt-6-astra",435    input="Generate an image of gray tabby cat hugging an otter with an orange scarf",436    tools=[437        {"type": "image_generation", "model": "gpt-image-2.5-sunburst", "action": "generate"}438    ],439)440441# Save the image to a file442image_data = [443    output.result444    for output in response.output445    if output.type == "image_generation_call"446]447448if image_data:449    image_base64 = image_data[0]450    with open("otter.png", "wb") as f:451        f.write(base64.b64decode(image_base64))452```453454```go455package main456457import (458	"context"459	"encoding/base64"460	"os"461462	"github.com/openai/openai-go/v3"463	"github.com/openai/openai-go/v3/responses"464)465466func main() {467	client := openai.NewClient()468	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{469		Model: "gpt-6-astra",470		Input: responses.ResponseNewParamsInputUnion{471			OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),472		},473		Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst", Action: "generate"}}},474	})475	if err != nil {476		panic(err)477	}478	for _, output := range response.Output {479		if output.Type != "image_generation_call" {480			continue481		}482		image, err := base64.StdEncoding.DecodeString(output.AsImageGenerationCall().Result)483		if err != nil {484			panic(err)485		}486		if err := os.WriteFile("otter.png", image, 0o600); err != nil {487			panic(err)488		}489		return490	}491	panic("response did not include an image generation call")492}493```494495```java496import com.openai.client.OpenAIClient;497import com.openai.client.okhttp.OpenAIOkHttpClient;498import com.openai.models.responses.ResponseCreateParams;499import com.openai.models.responses.Tool;500import java.io.IOException;501import java.nio.file.Files;502import java.nio.file.Path;503import java.util.Base64;504505ResponseCreateParams params =506    ResponseCreateParams.builder()507        .model("gpt-6-astra")508        .input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")509        .addTool(510            Tool.ImageGeneration.builder().action(Tool.ImageGeneration.Action.GENERATE).build())511        .build();512513String imageResult =514    client.responses().create(params).output().stream()515        .flatMap(item -> item.imageGenerationCall().stream())516        .flatMap(call -> call.result().stream())517        .findFirst()518        .orElseThrow(() -> new IllegalStateException("No generated image returned"));519Path output = Path.of(System.getenv().getOrDefault("OPENAI_EXAMPLE_OUTPUT_PATH", "otter.png"));520Files.write(output, Base64.getDecoder().decode(imageResult));521System.out.println(output);522```523524```csharp525using OpenAI.Responses;526#pragma warning disable OPENAI001527528string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;529ResponsesClient client = new(key);530531CreateResponseOptions options = new() { Model = "gpt-6-astra" };532options.InputItems.Add(533    ResponseItem.CreateUserMessageItem(534        "Generate an image of a gray tabby cat hugging an otter with an orange scarf."535    )536);537options.Tools.Add(538    ResponseTool.CreateImageGenerationTool(539        model: "gpt-image-2.5-sunburst",540        action: ImageGenerationToolAction.Generate541    )542);543544ResponseResult response = await client.CreateResponseAsync(options);545ImageGenerationCallResponseItem image = response546    .OutputItems.OfType<ImageGenerationCallResponseItem>()547    .FirstOrDefault()548    ?? throw new InvalidOperationException("No generated image was returned.");549await File.WriteAllBytesAsync("otter.png", image.ImageResultBytes.ToArray());550```551552```ruby553require "base64"554require "openai"555556client = OpenAI::Client.new557response = client.responses.create(558  model: "gpt-6-astra",559  input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",560  tools: [561    {562      type: :image_generation,563      model: "gpt-image-2.5-sunburst",564      action: :generate565    }566  ]567)568569image_call = response.output.find do |item|570  item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)571end572unless image_call.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)573  raise "No image generation call returned"574end575576encoded_image = image_call.result or raise "No image returned"577output_path = ENV.fetch("OPENAI_EXAMPLE_OUTPUT_PATH", "otter.png")578File.binwrite(output_path, Base64.decode64(encoded_image))579puts(output_path)580```581582583If you force `edit` without providing an image in context, the call will return an error. Leave `action` at `auto` to have the model decide when to generate or edit.584585586587Using previous response ID588589    Multi-turn image generation590591```javascript592import OpenAI from "openai";593const openai = new OpenAI();594595const response = await openai.responses.create({596  model: "gpt-6-astra",597  input:598    "Generate an image of gray tabby cat hugging an otter with an orange scarf",599  tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],600});601602const imageData = response.output603  .filter((output) => output.type === "image_generation_call")604  .map((output) => output.result);605606if (imageData.length > 0) {607  const imageBase64 = imageData[0];608  const fs = await import("fs");609  fs.writeFileSync("cat_and_otter.png", Buffer.from(imageBase64, "base64"));610}611612// Follow up613614const response_fwup = await openai.responses.create({615  model: "gpt-6-astra",616  previous_response_id: response.id,617  input: "Now make it look realistic",618  tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],619});620621const imageData_fwup = response_fwup.output622  .filter((output) => output.type === "image_generation_call")623  .map((output) => output.result);624625if (imageData_fwup.length > 0) {626  const imageBase64 = imageData_fwup[0];627  const fs = await import("fs");628  fs.writeFileSync(629    "cat_and_otter_realistic.png",630    Buffer.from(imageBase64, "base64")631  );632}633```634635```python636from openai import OpenAI637import base64638639client = OpenAI()640641response = client.responses.create(642    model="gpt-6-astra",643    input="Generate an image of gray tabby cat hugging an otter with an orange scarf",644    tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],645)646647image_data = [648    output.result649    for output in response.output650    if output.type == "image_generation_call"651]652653if image_data:654    image_base64 = image_data[0]655656    with open("cat_and_otter.png", "wb") as f:657        f.write(base64.b64decode(image_base64))658659660# Follow up661662response_fwup = client.responses.create(663    model="gpt-6-astra",664    previous_response_id=response.id,665    input="Now make it look realistic",666    tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],667)668669image_data_fwup = [670    output.result671    for output in response_fwup.output672    if output.type == "image_generation_call"673]674675if image_data_fwup:676    image_base64 = image_data_fwup[0]677    with open("cat_and_otter_realistic.png", "wb") as f:678        f.write(base64.b64decode(image_base64))679```680681```go682package main683684import (685	"context"686	"encoding/base64"687	"os"688689	"github.com/openai/openai-go/v3"690	"github.com/openai/openai-go/v3/responses"691)692693func main() {694	client := openai.NewClient()695	first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{696		Model: "gpt-6-astra",697		Input: responses.ResponseNewParamsInputUnion{698			OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),699		},700		Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},701	})702	if err != nil {703		panic(err)704	}705	saveFirstGeneratedImage(first, "cat_and_otter.png")706707	followUp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{708		Model:              "gpt-6-astra",709		PreviousResponseID: openai.String(first.ID),710		Input: responses.ResponseNewParamsInputUnion{711			OfString: openai.String("Now make it look realistic"),712		},713		Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},714	})715	if err != nil {716		panic(err)717	}718	saveFirstGeneratedImage(followUp, "cat_and_otter_realistic.png")719}720721func saveFirstGeneratedImage(response *responses.Response, filename string) {722	for _, output := range response.Output {723		if output.Type != "image_generation_call" {724			continue725		}726		image, err := base64.StdEncoding.DecodeString(output.AsImageGenerationCall().Result)727		if err != nil {728			panic(err)729		}730		if err := os.WriteFile(filename, image, 0o600); err != nil {731			panic(err)732		}733		return734	}735	panic("response did not include an image generation call")736}737```738739```java740import com.openai.client.OpenAIClient;741import com.openai.client.okhttp.OpenAIOkHttpClient;742import com.openai.models.responses.ResponseCreateParams;743import com.openai.models.responses.Tool;744import java.nio.file.Files;745import java.nio.file.Path;746import java.util.Base64;747748var first =749    client750        .responses()751        .create(752            ResponseCreateParams.builder()753                .model("gpt-6-astra")754                .input(755                    "Generate an image of a gray tabby cat hugging an otter with an orange scarf.")756                .addTool(Tool.ImageGeneration.builder().build())757                .build());758var firstImage =759    first.output().stream()760        .flatMap(item -> item.imageGenerationCall().stream())761        .findFirst()762        .orElseThrow(() -> new IllegalStateException("No image generation call returned"));763Files.write(764    Path.of("cat_and_otter.png"),765    Base64.getDecoder()766        .decode(767            firstImage768                .result()769                .orElseThrow(() -> new IllegalStateException("No image returned"))));770771var second =772    client773        .responses()774        .create(775            ResponseCreateParams.builder()776                .model("gpt-6-astra")777                .input("Now make it look realistic.")778                .previousResponseId(first.id())779                .addTool(Tool.ImageGeneration.builder().build())780                .build());781var secondImage =782    second.output().stream()783        .flatMap(item -> item.imageGenerationCall().stream())784        .findFirst()785        .orElseThrow(786            () -> new IllegalStateException("No follow-up image generation call returned"));787Files.write(788    Path.of("cat_and_otter_realistic.png"),789    Base64.getDecoder()790        .decode(791            secondImage792                .result()793                .orElseThrow(() -> new IllegalStateException("No follow-up image returned"))));794```795796```csharp797using OpenAI.Responses;798#pragma warning disable OPENAI001799800string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;801ResponsesClient client = new(key);802803CreateResponseOptions options = new() { Model = "gpt-6-astra" };804options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));805options.InputItems.Add(806    ResponseItem.CreateUserMessageItem(807        "Generate an image of a gray tabby cat hugging an otter with an orange scarf."808    )809);810811ResponseResult first = await client.CreateResponseAsync(options);812ImageGenerationCallResponseItem initialImage = first813    .OutputItems.OfType<ImageGenerationCallResponseItem>()814    .First();815await File.WriteAllBytesAsync("cat_and_otter.png", initialImage.ImageResultBytes.ToArray());816817CreateResponseOptions followUp = new()818{819    Model = "gpt-6-astra",820    PreviousResponseId = first.Id,821};822followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));823followUp.InputItems.Add(ResponseItem.CreateUserMessageItem("Now make it look realistic."));824825ResponseResult second = await client.CreateResponseAsync(followUp);826ImageGenerationCallResponseItem updatedImage = second827    .OutputItems.OfType<ImageGenerationCallResponseItem>()828    .First();829await File.WriteAllBytesAsync(830    "cat_and_otter_realistic.png",831    updatedImage.ImageResultBytes.ToArray()832);833```834835```ruby836require "base64"837require "openai"838839client = OpenAI::Client.new840first = client.responses.create(841  model: "gpt-6-astra",842  input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",843  tools: [844    {845      type: :image_generation,846      model: "gpt-image-2.5-sunburst"847    }848  ]849)850851first_image = first.output.find do |item|852  item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)853end854unless first_image.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)855  raise "No image generation call returned"856end857858encoded_image = first_image.result or raise "No image returned"859File.binwrite("cat_and_otter.png", Base64.strict_decode64(encoded_image))860861follow_up = client.responses.create(862  model: "gpt-6-astra",863  input: "Now make it look realistic.",864  previous_response_id: first.id,865  tools: [866    {867      type: :image_generation,868      model: "gpt-image-2.5-sunburst"869    }870  ]871)872873follow_up_image = follow_up.output.find do |item|874  item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)875end876unless follow_up_image.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)877  raise "No follow-up image generation call returned"878end879880encoded_image = follow_up_image.result or raise "No follow-up image returned"881File.binwrite("cat_and_otter_realistic.png", Base64.strict_decode64(encoded_image))882```883884  885886  887888    889Using image ID890891    Multi-turn image generation892893```javascript894import OpenAI from "openai";895const openai = new OpenAI();896897const response = await openai.responses.create({898  model: "gpt-6-astra",899  input:900    "Generate an image of gray tabby cat hugging an otter with an orange scarf",901  tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],902});903904const imageGenerationCalls = response.output.filter(905  (output) => output.type === "image_generation_call"906);907908const imageData = imageGenerationCalls.map((output) => output.result);909910if (imageData.length > 0) {911  const imageBase64 = imageData[0];912  const fs = await import("fs");913  fs.writeFileSync("cat_and_otter.png", Buffer.from(imageBase64, "base64"));914}915916// Follow up917918const response_fwup = await openai.responses.create({919  model: "gpt-6-astra",920  input: [921    {922      role: "user",923      content: [{ type: "input_text", text: "Now make it look realistic" }],924    },925    {926      type: "image_generation_call",927      id: imageGenerationCalls[0].id,928    },929  ],930  tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],931});932933const imageData_fwup = response_fwup.output934  .filter((output) => output.type === "image_generation_call")935  .map((output) => output.result);936937if (imageData_fwup.length > 0) {938  const imageBase64 = imageData_fwup[0];939  const fs = await import("fs");940  fs.writeFileSync(941    "cat_and_otter_realistic.png",942    Buffer.from(imageBase64, "base64")943  );944}945```946947```python948import openai949import base64950951response = openai.responses.create(952    model="gpt-6-astra",953    input="Generate an image of gray tabby cat hugging an otter with an orange scarf",954    tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],955)956957image_generation_calls = [958    output for output in response.output if output.type == "image_generation_call"959]960961image_data = [output.result for output in image_generation_calls]962963if image_data:964    image_base64 = image_data[0]965966    with open("cat_and_otter.png", "wb") as f:967        f.write(base64.b64decode(image_base64))968969970# Follow up971972response_fwup = openai.responses.create(973    model="gpt-6-astra",974    input=[975        {976            "role": "user",977            "content": [{"type": "input_text", "text": "Now make it look realistic"}],978        },979        {980            "type": "image_generation_call",981            "id": image_generation_calls[0].id,982        },983    ],984    tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],985)986987image_data_fwup = [988    output.result989    for output in response_fwup.output990    if output.type == "image_generation_call"991]992993if image_data_fwup:994    image_base64 = image_data_fwup[0]995    with open("cat_and_otter_realistic.png", "wb") as f:996        f.write(base64.b64decode(image_base64))997```998999```go1000package main10011002import (1003	"context"1004	"encoding/base64"1005	"encoding/json"1006	"os"10071008	"github.com/openai/openai-go/v3"1009	"github.com/openai/openai-go/v3/responses"1010)10111012func main() {1013	client := openai.NewClient()1014	first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1015		Model: "gpt-6-astra",1016		Input: responses.ResponseNewParamsInputUnion{1017			OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),1018		},1019		Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},1020	})1021	if err != nil {1022		panic(err)1023	}1024	call := firstImageGenerationCall(first)1025	saveImage("cat_and_otter.png", call.Result)1026	input := outputAsInput(first.Output)1027	input = append(input, responses.ResponseInputItemParamOfMessage(1028		responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("Now make it look realistic")},1029		responses.EasyInputMessageRoleUser,1030	))10311032	followUp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1033		Model: "gpt-6-astra",1034		Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},1035		Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},1036	})1037	if err != nil {1038		panic(err)1039	}1040	saveImage("cat_and_otter_realistic.png", firstImageGenerationCall(followUp).Result)1041}10421043func firstImageGenerationCall(response *responses.Response) responses.ResponseOutputItemImageGenerationCall {1044	for _, output := range response.Output {1045		if output.Type == "image_generation_call" {1046			return output.AsImageGenerationCall()1047		}1048	}1049	panic("response did not include an image generation call")1050}10511052func outputAsInput(output []responses.ResponseOutputItemUnion) []responses.ResponseInputItemUnionParam {1053	input := make([]responses.ResponseInputItemUnionParam, 0, len(output))1054	for _, item := range output {1055		var converted responses.ResponseInputItemUnion1056		if err := json.Unmarshal([]byte(item.RawJSON()), &converted); err != nil {1057			panic(err)1058		}1059		input = append(input, converted.ToParam())1060	}1061	return input1062}10631064func saveImage(filename, encoded string) {1065	image, err := base64.StdEncoding.DecodeString(encoded)1066	if err != nil {1067		panic(err)1068	}1069	if err := os.WriteFile(filename, image, 0o600); err != nil {1070		panic(err)1071	}1072}1073```10741075```java1076import com.openai.client.OpenAIClient;1077import com.openai.client.okhttp.OpenAIOkHttpClient;1078import com.openai.core.JsonValue;1079import com.openai.models.responses.ResponseCreateParams;1080import com.openai.models.responses.ResponseInputItem;1081import com.openai.models.responses.Tool;1082import java.nio.file.Files;1083import java.nio.file.Path;1084import java.util.Base64;1085import java.util.List;1086import java.util.Map;10871088var first =1089    client1090        .responses()1091        .create(1092            ResponseCreateParams.builder()1093                .model("gpt-6-astra")1094                .input(1095                    "Generate an image of a gray tabby cat hugging an otter with an orange scarf.")1096                .addTool(Tool.ImageGeneration.builder().build())1097                .build());1098var firstImage =1099    first.output().stream()1100        .flatMap(item -> item.imageGenerationCall().stream())1101        .findFirst()1102        .orElseThrow(() -> new IllegalStateException("No image generation call returned"));1103Files.write(1104    Path.of("cat_and_otter.png"),1105    Base64.getDecoder()1106        .decode(1107            firstImage1108                .result()1109                .orElseThrow(() -> new IllegalStateException("No image returned"))));11101111var second =1112    client1113        .responses()1114        .create(1115            ResponseCreateParams.builder()1116                .model("gpt-6-astra")1117                .inputOfResponse(1118                    List.of(1119                        ResponseInputItem.ofMessage(1120                            ResponseInputItem.Message.builder()1121                                .role(ResponseInputItem.Message.Role.USER)1122                                .addInputTextContent("Now make it look realistic.")1123                                .build()),1124                        JsonValue.from(1125                                Map.of("type", "image_generation_call", "id", firstImage.id()))1126                            .convert(ResponseInputItem.class)))1127                .addTool(Tool.ImageGeneration.builder().build())1128                .build());1129var secondImage =1130    second.output().stream()1131        .flatMap(item -> item.imageGenerationCall().stream())1132        .findFirst()1133        .orElseThrow(1134            () -> new IllegalStateException("No follow-up image generation call returned"));1135Files.write(1136    Path.of("cat_and_otter_realistic.png"),1137    Base64.getDecoder()1138        .decode(1139            secondImage1140                .result()1141                .orElseThrow(() -> new IllegalStateException("No follow-up image returned"))));1142```11431144```csharp1145using OpenAI.Responses;1146#pragma warning disable OPENAI00111471148string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1149ResponsesClient client = new(key);11501151CreateResponseOptions options = new() { Model = "gpt-6-astra" };1152options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));1153options.InputItems.Add(1154    ResponseItem.CreateUserMessageItem(1155        "Generate an image of a gray tabby cat hugging an otter with an orange scarf."1156    )1157);11581159ResponseResult first = await client.CreateResponseAsync(options);1160ImageGenerationCallResponseItem initialImage = first1161    .OutputItems.OfType<ImageGenerationCallResponseItem>()1162    .First();1163await File.WriteAllBytesAsync("cat_and_otter.png", initialImage.ImageResultBytes.ToArray());11641165CreateResponseOptions followUp = new() { Model = "gpt-6-astra" };1166followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));1167followUp.InputItems.Add(ResponseItem.CreateUserMessageItem("Now make it look realistic."));1168followUp.InputItems.Add(ResponseItem.CreateReferenceItem(initialImage.Id));11691170ResponseResult second = await client.CreateResponseAsync(followUp);1171ImageGenerationCallResponseItem updatedImage = second1172    .OutputItems.OfType<ImageGenerationCallResponseItem>()1173    .First();1174await File.WriteAllBytesAsync(1175    "cat_and_otter_realistic.png",1176    updatedImage.ImageResultBytes.ToArray()1177);1178```11791180```ruby1181require "base64"1182require "openai"11831184client = OpenAI::Client.new1185first = client.responses.create(1186  model: "gpt-6-astra",1187  input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",1188  tools: [1189    {1190      type: :image_generation,1191      model: "gpt-image-2.5-sunburst"1192    }1193  ]1194)11951196first_image = first.output.find do |item|1197  item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)1198end1199unless first_image.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)1200  raise "No image generation call returned"1201end12021203encoded_image = first_image.result or raise "No image returned"1204File.binwrite("cat_and_otter.png", Base64.strict_decode64(encoded_image))12051206follow_up = client.responses.create(1207  model: "gpt-6-astra",1208  input: [1209    {1210      role: :user,1211      content: [1212        {1213          type: :input_text,1214          text: "Now make it look realistic."1215        }1216      ]1217    },1218    {1219      type: :image_generation_call,1220      id: first_image.id1221    }1222  ],1223  tools: [1224    {1225      type: :image_generation,1226      model: "gpt-image-2.5-sunburst"1227    }1228  ]1229)12301231follow_up_image = follow_up.output.find do |item|1232  item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)1233end1234unless follow_up_image.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)1235  raise "No follow-up image generation call returned"1236end12371238encoded_image = follow_up_image.result or raise "No follow-up image returned"1239File.binwrite("cat_and_otter_realistic.png", Base64.strict_decode64(encoded_image))1240```1241124212431244#### Result1245124612471248  <table style={{ width: "100%" }}>1249    <tbody>1250      <tr>1251        <td style={{ verticalAlign: "top", padding: "0 16px 16px 0" }}>1252          "Generate an image of gray tabby cat hugging an otter with an orange1253          scarf"1254        </td>1255        <td1256          style={{1257            textAlign: "right",1258            verticalAlign: "top",1259            paddingBottom: "16px",1260          }}1261        >1262          <img src="https://developers.openai.com/images/image-25-article/cat_and_otter.png"1263            alt="A cat and an otter"1264            style={{ width: "200px", borderRadius: "8px" }}1265          />1266        </td>1267      </tr>1268      <tr>1269        <td style={{ verticalAlign: "top", padding: "0 16px 0 0" }}>1270          "Now make it look realistic"1271        </td>1272        <td style={{ textAlign: "right", verticalAlign: "top" }}>1273          <img src="https://developers.openai.com/images/image-25-article/cat_and_otter_realistic.png"1274            alt="A cat and an otter"1275            style={{ width: "200px", borderRadius: "8px" }}1276          />1277        </td>1278      </tr>1279    </tbody>1280  </table>1281128212831284### Streaming12851286The Responses API and Image API support streaming image generation. You can stream partial images as the APIs generate them, providing a more interactive experience.12871288You can adjust the `partial_images` parameter to receive 0-3 partial images.12891290- If you set `partial_images` to 0, you will only receive the final image.1291- For values larger than zero, you may not receive the full number of partial images you requested if the full image is generated more quickly.1292129312941295Responses API12961297    Stream an image12981299```javascript1300import OpenAI from "openai";1301import fs from "fs";1302const openai = new OpenAI();13031304function saveBase64Image(filename, imageBase64) {1305  const imageBuffer = Buffer.from(imageBase64, "base64");1306  fs.writeFileSync(filename, imageBuffer);1307}13081309const stream = await openai.responses.create({1310  model: "gpt-6-astra",1311  input:1312    "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",1313  stream: true,1314  tools: [1315    { type: "image_generation", model: "gpt-image-2.5-sunburst", partial_images: 2 },1316  ],1317});13181319for await (const event of stream) {1320  if (event.type === "response.image_generation_call.partial_image") {1321    const idx = event.partial_image_index;1322    saveBase64Image(`river-partial-${idx}.png`, event.partial_image_b64);1323  } else if (event.type === "response.completed") {1324    const imageData = event.response.output1325      .filter((output) => output.type === "image_generation_call")1326      .map((output) => output.result);13271328    if (imageData.length > 0) {1329      saveBase64Image("river-final.png", imageData[0]);1330    }1331  }1332}1333```13341335```python1336from openai import OpenAI1337import base6413381339client = OpenAI()134013411342def save_base64_image(filename, image_base64):1343    image_bytes = base64.b64decode(image_base64)1344    with open(filename, "wb") as f:1345        f.write(image_bytes)134613471348stream = client.responses.create(1349    model="gpt-6-astra",1350    input="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",1351    stream=True,1352    tools=[1353        {"type": "image_generation", "model": "gpt-image-2.5-sunburst", "partial_images": 2}1354    ],1355)13561357for event in stream:1358    if event.type == "response.image_generation_call.partial_image":1359        idx = event.partial_image_index1360        save_base64_image(f"river-partial-{idx}.png", event.partial_image_b64)1361    elif event.type == "response.completed":1362        image_data = [1363            output.result1364            for output in event.response.output1365            if output.type == "image_generation_call"1366        ]13671368        if image_data:1369            save_base64_image("river-final.png", image_data[0])1370```13711372```go1373package main13741375import (1376	"context"1377	"encoding/base64"1378	"fmt"1379	"os"13801381	"github.com/openai/openai-go/v3"1382	"github.com/openai/openai-go/v3/responses"1383)13841385func main() {1386	client := openai.NewClient()1387	stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{1388		Model: "gpt-6-astra",1389		Input: responses.ResponseNewParamsInputUnion{1390			OfString: openai.String("Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape"),1391		},1392		Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst", PartialImages: openai.Int(2)}}},1393	})1394	for stream.Next() {1395		event := stream.Current()1396		if event.Type == "response.image_generation_call.partial_image" {1397			partial := event.AsResponseImageGenerationCallPartialImage()1398			saveImage(fmt.Sprintf("river-partial-%d.png", partial.PartialImageIndex), partial.PartialImageB64)1399		}1400		if event.Type == "response.completed" {1401			for _, output := range event.AsResponseCompleted().Response.Output {1402				if output.Type == "image_generation_call" {1403					saveImage("river-final.png", output.AsImageGenerationCall().Result)1404				}1405			}1406		}1407	}1408	if err := stream.Err(); err != nil {1409		panic(err)1410	}1411}14121413func saveImage(filename, encoded string) {1414	image, err := base64.StdEncoding.DecodeString(encoded)1415	if err != nil {1416		panic(err)1417	}1418	if err := os.WriteFile(filename, image, 0o600); err != nil {1419		panic(err)1420	}1421}1422```14231424```java1425import com.openai.client.OpenAIClient;1426import com.openai.client.okhttp.OpenAIOkHttpClient;1427import com.openai.core.http.StreamResponse;1428import com.openai.models.responses.ResponseCreateParams;1429import com.openai.models.responses.ResponseStreamEvent;1430import com.openai.models.responses.Tool;1431import java.io.IOException;1432import java.nio.file.Files;1433import java.nio.file.Path;1434import java.util.Base64;14351436ResponseCreateParams params =1437    ResponseCreateParams.builder()1438        .model("gpt-6-astra")1439        .input("Generate an image of a river made of white owl feathers.")1440        .addTool(Tool.ImageGeneration.builder().partialImages(2).build())1441        .build();14421443try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {1444  var events = stream.stream().iterator();1445  while (events.hasNext()) {1446    ResponseStreamEvent event = events.next();1447    if (event.imageGenerationCallPartialImage().isPresent()) {1448      var partial = event.imageGenerationCallPartialImage().orElseThrow();1449      Files.write(1450          Path.of("river-partial-" + partial.partialImageIndex() + ".png"),1451          Base64.getDecoder().decode(partial.partialImageB64()));1452    }1453    if (event.completed().isPresent()) {1454      var image =1455          event.completed().orElseThrow().response().output().stream()1456              .flatMap(item -> item.imageGenerationCall().stream())1457              .findFirst()1458              .orElseThrow(() -> new IllegalStateException("No generated image returned"));1459      Files.write(1460          Path.of("river-final.png"),1461          Base64.getDecoder()1462              .decode(1463                  image1464                      .result()1465                      .orElseThrow(1466                          () -> new IllegalStateException("No final image returned"))));1467    }1468  }1469}1470```14711472```ruby1473require "base64"1474require "openai"14751476client = OpenAI::Client.new1477stream = client.responses.stream(1478  model: "gpt-6-astra",1479  input: "Generate an image of a river made of white owl feathers.",1480  tools: [1481    {1482      type: :image_generation,1483      model: "gpt-image-2.5-sunburst",1484      partial_images: 21485    }1486  ]1487)14881489stream.each do |event|1490  case event1491  when OpenAI::Models::Responses::ResponseImageGenCallPartialImageEvent1492    image = Base64.strict_decode64(event.partial_image_b64)1493    File.binwrite("river-partial-#{event.partial_image_index}.png", image)1494  when OpenAI::Models::Responses::ResponseCompletedEvent1495    image_call = event.response.output.find do |item|1496      item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)1497    end1498    next unless image_call.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)14991500    File.binwrite(1501      "river-final.png",1502      Base64.strict_decode64(image_call.result)1503    )1504  end1505end1506```15071508  15091510  15111512    1513Image API15141515    Stream an image15161517```javascript1518import fs from "fs";1519import OpenAI from "openai";15201521const openai = new OpenAI();15221523const prompt =1524  "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape";1525const stream = await openai.images.generate({1526  prompt: prompt,1527  model: "gpt-image-2.5-sunburst",1528  stream: true,1529  partial_images: 2,1530});15311532for await (const event of stream) {1533  if (event.type === "image_generation.partial_image") {1534    const idx = event.partial_image_index;1535    const imageBase64 = event.b64_json;1536    const imageBuffer = Buffer.from(imageBase64, "base64");1537    fs.writeFileSync(`river${idx}.png`, imageBuffer);1538  }1539}1540```15411542```python1543from openai import OpenAI1544import base6415451546client = OpenAI()15471548stream = client.images.generate(1549    prompt="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",1550    model="gpt-image-2.5-sunburst",1551    stream=True,1552    partial_images=2,1553)15541555for event in stream:1556    if event.type == "image_generation.partial_image":1557        idx = event.partial_image_index1558        image_base64 = event.b64_json1559        image_bytes = base64.b64decode(image_base64)1560        with open(f"river{idx}.png", "wb") as f:1561            f.write(image_bytes)1562```15631564```go1565package main15661567import (1568	"context"1569	"encoding/base64"1570	"fmt"1571	"os"15721573	"github.com/openai/openai-go/v3"1574)15751576func main() {1577	client := openai.NewClient()1578	stream := client.Images.GenerateStreaming(context.Background(), openai.ImageGenerateParams{1579		Model:         openai.ImageModel("gpt-image-2.5-sunburst"),1580		Prompt:        "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",1581		PartialImages: openai.Int(2),1582	})1583	for stream.Next() {1584		event := stream.Current()1585		if event.Type != "image_generation.partial_image" {1586			continue1587		}1588		partial := event.AsImageGenerationPartialImage()1589		saveImage(fmt.Sprintf("river%d.png", partial.PartialImageIndex), partial.B64JSON)1590	}1591	if err := stream.Err(); err != nil {1592		panic(err)1593	}1594}15951596func saveImage(filename, encoded string) {1597	image, err := base64.StdEncoding.DecodeString(encoded)1598	if err != nil {1599		panic(err)1600	}1601	if err := os.WriteFile(filename, image, 0o600); err != nil {1602		panic(err)1603	}1604}1605```16061607```ruby1608require "base64"1609require "openai"16101611client = OpenAI::Client.new1612stream = client.images.generate_stream_raw(1613  model: "gpt-image-2.5-sunburst",1614  prompt: "A river made of white owl feathers in a winter landscape",1615  partial_images: 21616)16171618stream.each do |event|1619  next unless event.is_a?(OpenAI::Models::ImageGenPartialImageEvent)16201621  image = Base64.strict_decode64(event.b64_json)1622  File.binwrite("river#{event.partial_image_index}.png", image)1623end1624```1625162616271628#### Result16291630163116321633| Partial 1                                                                                                     | Partial 2                                                                                                     | Final image                                                                                               |1634| ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |1635| <img className="images-example-image" src="https://developers.openai.com/images/image-25-article/river-partial-0.png" alt="1st partial" /> | <img className="images-example-image" src="https://developers.openai.com/images/image-25-article/river-partial-1.png" alt="2nd partial" /> | <img className="images-example-image" src="https://developers.openai.com/images/image-25-article/river-final.png" alt="Final image" /> |1636163716381639164016411642  Prompt: Draw a gorgeous image of a river made of white owl feathers, snaking1643  its way through a serene winter landscape1644164516461647### Revised prompt16481649When using the image generation tool in the Responses API, the mainline model (for example, `gpt-5.5`) will automatically revise your prompt for improved performance.16501651You can access the revised prompt in the `revised_prompt` field of the image generation call:16521653Revised prompt response16541655```json1656{1657  "id": "ig_123",1658  "type": "image_generation_call",1659  "status": "completed",1660  "revised_prompt": "A gray tabby cat hugging an otter. The otter is wearing an orange scarf. Both animals are cute and friendly, depicted in a warm, heartwarming style.",1661  "result": "..."1662}1663```166416651666## Edit Images16671668The [image edits](https://developers.openai.com/api/reference/resources/images) endpoint lets you:16691670- Edit existing images1671- Generate new images using other images as a reference1672- Edit parts of an image by uploading an image and mask that identifies the areas to replace16731674### Create a new image using image references16751676You can use one or more images as a reference to generate a new image.16771678In this example, we'll use 4 input images to generate a new image of a gift basket containing the items in the reference images.16791680Responses API16811682    16831684With the Responses API, you can provide input images in 3 different ways:16851686- By providing a fully qualified URL1687- By providing an image as a Base64-encoded data URL1688- By providing a file ID (created with the [Files API](https://developers.openai.com/api/reference/resources/files))16891690#### Create a File16911692Create a File16931694```javascript1695import fs from "fs";1696import OpenAI from "openai";16971698const openai = new OpenAI();16991700async function createFile(filePath) {1701  const fileContent = fs.createReadStream(filePath);1702  const result = await openai.files.create({1703    file: fileContent,1704    purpose: "vision",1705  });1706  return result.id;1707}1708```17091710```python1711from openai import OpenAI17121713client = OpenAI()171417151716def create_file(file_path):1717    with open(file_path, "rb") as file_content:1718        result = client.files.create(1719            file=file_content,1720            purpose="vision",1721        )1722        return result.id1723```17241725```go1726package main17271728import (1729	"context"1730	"fmt"1731	"os"17321733	"github.com/openai/openai-go/v3"1734)17351736func main() {1737	client := openai.NewClient()1738	file, err := os.Open("image.png")1739	if err != nil {1740		panic(err)1741	}1742	defer file.Close()17431744	uploaded, err := client.Files.New(context.Background(), openai.FileNewParams{1745		File:    file,1746		Purpose: openai.FilePurposeVision,1747	})1748	if err != nil {1749		panic(err)1750	}1751	fmt.Println(uploaded.ID)1752}1753```17541755```java1756import com.openai.client.OpenAIClient;1757import com.openai.client.okhttp.OpenAIOkHttpClient;1758import com.openai.models.files.FileCreateParams;1759import com.openai.models.files.FilePurpose;1760import java.nio.file.Path;17611762var file =1763    client1764        .files()1765        .create(1766            FileCreateParams.builder()1767                .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))1768                .purpose(FilePurpose.VISION)1769                .build());17701771System.out.println(file.id());1772```17731774```ruby1775require "openai"1776require "pathname"17771778client = OpenAI::Client.new1779file = client.files.create(1780  file: Pathname("image.png"),1781  purpose: OpenAI::Models::FilePurpose::VISION1782)1783puts(file.id)1784```178517861787#### Create a base64 encoded image17881789Create a base64 encoded image17901791```javascript1792import fs from "fs";17931794function encodeImage(filePath) {1795  const base64Image = fs.readFileSync(filePath, "base64");1796  return base64Image;1797}1798```17991800```python1801import base64180218031804def encode_image(file_path):1805    with open(file_path, "rb") as f:1806        base64_image = base64.b64encode(f.read()).decode("utf-8")1807    return base64_image1808```18091810```go1811package main18121813import (1814	"encoding/base64"1815	"fmt"1816	"os"1817)18181819func main() {1820	image, err := os.ReadFile("image.png")1821	if err != nil {1822		panic(err)1823	}1824	fmt.Println(base64.StdEncoding.EncodeToString(image))1825}1826```18271828```ruby1829require "base64"18301831image = File.binread("image.png")1832puts(Base64.strict_encode64(image))1833```183418351836Edit an image18371838```javascript1839import fs from "fs";1840import OpenAI from "openai";18411842const openai = new OpenAI();18431844function encodeImage(filePath) {1845  return fs.readFileSync(filePath, "base64");1846}18471848async function createFile(filePath) {1849  const result = await openai.files.create({1850    file: fs.createReadStream(filePath),1851    purpose: "vision",1852  });1853  return result.id;1854}18551856const prompt = `Generate a photorealistic image of a gift basket on a white background1857labeled 'Relax & Unwind' with a ribbon and handwriting-like font,1858containing all the items in the reference pictures.`;18591860const base64Image1 = encodeImage("fixtures/body-lotion.png");1861const base64Image2 = encodeImage("fixtures/soap.png");1862const fileId1 = await createFile("fixtures/bath-bomb.png");1863const fileId2 = await createFile("fixtures/incense-kit.png");18641865const response = await openai.responses.create({1866  model: "gpt-6-astra",1867  input: [1868    {1869      role: "user",1870      content: [1871        { type: "input_text", text: prompt },1872        {1873          type: "input_image",1874          image_url: `data:image/png;base64,${base64Image1}`,1875          detail: "auto",1876        },1877        {1878          type: "input_image",1879          image_url: `data:image/png;base64,${base64Image2}`,1880          detail: "auto",1881        },1882        {1883          type: "input_image",1884          file_id: fileId1,1885          detail: "auto",1886        },1887        {1888          type: "input_image",1889          file_id: fileId2,1890          detail: "auto",1891        },1892      ],1893    },1894  ],1895  tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],1896});18971898const imageData = response.output1899  .filter((output) => output.type === "image_generation_call")1900  .map((output) => output.result);19011902if (imageData.length > 0) {1903  const imageBase64 = imageData[0];1904  fs.writeFileSync("gift-basket.png", Buffer.from(imageBase64, "base64"));1905} else {1906  console.log(response.output_text);1907}1908```19091910```python1911from openai import OpenAI1912import base6419131914client = OpenAI()191519161917def encode_image(file_path):1918    with open(file_path, "rb") as image_file:1919        return base64.b64encode(image_file.read()).decode("utf-8")192019211922def create_file(file_path):1923    with open(file_path, "rb") as file_content:1924        result = client.files.create(file=file_content, purpose="vision")1925    return result.id192619271928prompt = """Generate a photorealistic image of a gift basket on a white background1929labeled 'Relax & Unwind' with a ribbon and handwriting-like font,1930containing all the items in the reference pictures."""19311932base64_image1 = encode_image("body-lotion.png")1933base64_image2 = encode_image("soap.png")1934file_id1 = create_file("bath-bomb.png")1935file_id2 = create_file("incense-kit.png")19361937response = client.responses.create(1938    model="gpt-6-astra",1939    input=[1940        {1941            "role": "user",1942            "content": [1943                {"type": "input_text", "text": prompt},1944                {1945                    "type": "input_image",1946                    "image_url": f"data:image/png;base64,{base64_image1}",1947                },1948                {1949                    "type": "input_image",1950                    "image_url": f"data:image/png;base64,{base64_image2}",1951                },1952                {1953                    "type": "input_image",1954                    "file_id": file_id1,1955                },1956                {1957                    "type": "input_image",1958                    "file_id": file_id2,1959                },1960            ],1961        }1962    ],1963    tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],1964)19651966image_generation_calls = [1967    output for output in response.output if output.type == "image_generation_call"1968]19691970image_data = [output.result for output in image_generation_calls]19711972if image_data:1973    image_base64 = image_data[0]1974    with open("gift-basket.png", "wb") as f:1975        f.write(base64.b64decode(image_base64))1976else:1977    print(response.output_text)1978```19791980```go1981package main19821983import (1984	"context"1985	"encoding/base64"1986	"os"19871988	"github.com/openai/openai-go/v3"1989	"github.com/openai/openai-go/v3/responses"1990)19911992func main() {1993	client := openai.NewClient()1994	bathBombID := uploadImage(client, "bath-bomb.png")1995	incenseKitID := uploadImage(client, "incense-kit.png")19961997	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1998		Model: "gpt-6-astra",1999		Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{2000			responses.ResponseInputItemParamOfMessage(2001				responses.ResponseInputMessageContentListParam{2002					responses.ResponseInputContentParamOfInputText("Generate a photorealistic image of a gift basket on a white background labeled 'Relax & Unwind' with a ribbon and handwriting-like font, containing all the items in the reference pictures."),2003					{OfInputImage: &responses.ResponseInputImageParam{ImageURL: openai.String(dataURL("body-lotion.png")), Detail: responses.ResponseInputImageDetailAuto}},2004					{OfInputImage: &responses.ResponseInputImageParam{ImageURL: openai.String(dataURL("soap.png")), Detail: responses.ResponseInputImageDetailAuto}},2005					{OfInputImage: &responses.ResponseInputImageParam{FileID: openai.String(bathBombID), Detail: responses.ResponseInputImageDetailAuto}},2006					{OfInputImage: &responses.ResponseInputImageParam{FileID: openai.String(incenseKitID), Detail: responses.ResponseInputImageDetailAuto}},2007				},2008				responses.EasyInputMessageRoleUser,2009			),2010		}},2011		Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},2012	})2013	if err != nil {2014		panic(err)2015	}2016	saveFirstGeneratedImage(response, "gift-basket.png")2017}20182019func uploadImage(client openai.Client, filename string) string {2020	file, err := os.Open(filename)2021	if err != nil {2022		panic(err)2023	}2024	defer file.Close()2025	uploaded, err := client.Files.New(context.Background(), openai.FileNewParams{File: file, Purpose: openai.FilePurposeVision})2026	if err != nil {2027		panic(err)2028	}2029	return uploaded.ID2030}20312032func dataURL(filename string) string {2033	image, err := os.ReadFile(filename)2034	if err != nil {2035		panic(err)2036	}2037	return "data:image/png;base64," + base64.StdEncoding.EncodeToString(image)2038}20392040func saveFirstGeneratedImage(response *responses.Response, filename string) {2041	for _, output := range response.Output {2042		if output.Type != "image_generation_call" {2043			continue2044		}2045		image, err := base64.StdEncoding.DecodeString(output.AsImageGenerationCall().Result)2046		if err != nil {2047			panic(err)2048		}2049		if err := os.WriteFile(filename, image, 0o600); err != nil {2050			panic(err)2051		}2052		return2053	}2054	panic("response did not include an image generation call")2055}2056```20572058```java2059import com.openai.client.OpenAIClient;2060import com.openai.client.okhttp.OpenAIOkHttpClient;2061import com.openai.models.files.FileCreateParams;2062import com.openai.models.files.FilePurpose;2063import com.openai.models.responses.ResponseCreateParams;2064import com.openai.models.responses.ResponseInputImage;2065import com.openai.models.responses.ResponseInputItem;2066import com.openai.models.responses.Tool;2067import java.nio.file.Files;2068import java.nio.file.Path;2069import java.util.Base64;2070import java.util.List;20712072Path lotionImage = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH"));2073Path soapImage = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_2"));2074Path bathBombImage = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_3"));2075Path incenseImage = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_4"));2076String lotionBase64 = Base64.getEncoder().encodeToString(Files.readAllBytes(lotionImage));2077String soapBase64 = Base64.getEncoder().encodeToString(Files.readAllBytes(soapImage));2078var firstFile =2079    client2080        .files()2081        .create(2082            FileCreateParams.builder().file(bathBombImage).purpose(FilePurpose.VISION).build());2083var secondFile =2084    client2085        .files()2086        .create(2087            FileCreateParams.builder().file(incenseImage).purpose(FilePurpose.VISION).build());2088String prompt =2089    """2090    Generate a photorealistic image of a gift basket on a white background2091    labeled 'Relax & Unwind' with a ribbon and handwriting-like font,2092    containing all the items in the reference pictures.2093    """;2094var input =2095    ResponseInputItem.ofMessage(2096        ResponseInputItem.Message.builder()2097            .role(ResponseInputItem.Message.Role.USER)2098            .addInputTextContent(prompt)2099            .addContent(2100                ResponseInputImage.builder()2101                    .detail(ResponseInputImage.Detail.AUTO)2102                    .imageUrl("data:image/png;base64," + lotionBase64)2103                    .build())2104            .addContent(2105                ResponseInputImage.builder()2106                    .detail(ResponseInputImage.Detail.AUTO)2107                    .imageUrl("data:image/png;base64," + soapBase64)2108                    .build())2109            .addContent(2110                ResponseInputImage.builder()2111                    .detail(ResponseInputImage.Detail.AUTO)2112                    .fileId(firstFile.id())2113                    .build())2114            .addContent(2115                ResponseInputImage.builder()2116                    .detail(ResponseInputImage.Detail.AUTO)2117                    .fileId(secondFile.id())2118                    .build())2119            .build());2120var response =2121    client2122        .responses()2123        .create(2124            ResponseCreateParams.builder()2125                .model("gpt-6-astra")2126                .inputOfResponse(List.of(input))2127                .addTool(Tool.ImageGeneration.builder().build())2128                .build());2129var image =2130    response.output().stream()2131        .flatMap(item -> item.imageGenerationCall().stream())2132        .findFirst()2133        .orElseThrow(() -> new IllegalStateException("No image generation call returned"));2134Files.write(2135    Path.of("gift-basket.png"),2136    Base64.getDecoder()2137        .decode(2138            image.result().orElseThrow(() -> new IllegalStateException("No image returned"))));2139```21402141```ruby2142require "base64"2143require "openai"2144require "pathname"21452146client = OpenAI::Client.new2147base64_images = ["body-lotion.png", "soap.png"].map do |path|2148  Base64.strict_encode64(File.binread(path))2149end2150file_ids = [2151  client.files.create(file: Pathname("bath-bomb.png"), purpose: :vision).id,2152  client.files.create(file: Pathname("incense-kit.png"), purpose: :vision).id2153]2154prompt = <<~PROMPT2155  Generate a photorealistic image of a gift basket on a white background2156  labeled 'Relax & Unwind' with a ribbon and handwriting-like font,2157  containing all the items in the reference pictures.2158PROMPT2159response = client.responses.create(2160  model: "gpt-6-astra",2161  input: [2162    {2163      role: :user,2164      content: [2165        {2166          type: :input_text,2167          text: prompt2168        },2169        *base64_images.map do |image|2170          {2171            type: :input_image,2172            image_url: "data:image/png;base64,#{image}"2173          }2174        end,2175        *file_ids.map do |file_id|2176          {2177            type: :input_image,2178            file_id: file_id2179          }2180        end2181      ]2182    }2183  ],2184  tools: [2185    {2186      type: :image_generation,2187      model: "gpt-image-2.5-sunburst"2188    }2189  ]2190)21912192image_call = response.output.find do |item|2193  item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)2194end2195unless image_call.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)2196  raise "No image generation call returned"2197end21982199File.binwrite("gift-basket.png", Base64.strict_decode64(image_call.result))2200```220122022203  22042205  22062207    2208Image API22092210    Edit an image22112212```javascript2213import fs from "fs";2214import OpenAI, { toFile } from "openai";22152216const client = new OpenAI();22172218const prompt = `2219Generate a photorealistic image of a gift basket on a white background2220labeled 'Relax & Unwind' with a ribbon and handwriting-like font,2221containing all the items in the reference pictures.2222`;22232224const imageFiles = [2225  "fixtures/bath-bomb.png",2226  "fixtures/body-lotion.png",2227  "fixtures/incense-kit.png",2228  "fixtures/soap.png",2229];22302231const images = await Promise.all(2232  imageFiles.map(2233    async (file) =>2234      await toFile(fs.createReadStream(file), null, {2235        type: "image/png",2236      })2237  )2238);22392240const response = await client.images.edit({2241  model: "gpt-image-2.5-sunburst",2242  image: images,2243  prompt,2244});22452246// Save the image to a file2247const image_base64 = response.data[0].b64_json;2248const image_bytes = Buffer.from(image_base64, "base64");2249fs.writeFileSync("basket.png", image_bytes);2250```22512252```python2253import base642254from openai import OpenAI22552256client = OpenAI()22572258prompt = """2259Generate a photorealistic image of a gift basket on a white background2260labeled 'Relax & Unwind' with a ribbon and handwriting-like font,2261containing all the items in the reference pictures.2262"""22632264result = client.images.edit(2265    model="gpt-image-2.5-sunburst",2266    image=[2267        open("body-lotion.png", "rb"),2268        open("bath-bomb.png", "rb"),2269        open("incense-kit.png", "rb"),2270        open("soap.png", "rb"),2271    ],2272    prompt=prompt,2273)22742275image_base64 = result.data[0].b64_json2276image_bytes = base64.b64decode(image_base64)22772278# Save the image to a file2279with open("gift-basket.png", "wb") as f:2280    f.write(image_bytes)2281```22822283```go2284package main22852286import (2287	"context"2288	"encoding/base64"2289	"io"2290	"os"22912292	"github.com/openai/openai-go/v3"2293)22942295func main() {2296	client := openai.NewClient()2297	files, closeFiles := openImages(2298		"bath-bomb.png",2299		"body-lotion.png",2300		"incense-kit.png",2301		"soap.png",2302	)2303	defer closeFiles()23042305	response, err := client.Images.Edit(context.Background(), openai.ImageEditParams{2306		Model: openai.ImageModel("gpt-image-2.5-sunburst"),2307		Image: openai.ImageEditParamsImageUnion{OfFileArray: files},2308		Prompt: "Generate a photorealistic image of a gift basket on a white background " +2309			"labeled 'Relax & Unwind' with a ribbon and handwriting-like font, containing all the items in the reference pictures.",2310	})2311	if err != nil {2312		panic(err)2313	}2314	saveImage("basket.png", response.Data[0].B64JSON)2315}23162317func openImages(names ...string) ([]io.Reader, func()) {2318	images := make([]io.Reader, 0, len(names))2319	files := make([]*os.File, 0, len(names))2320	for _, name := range names {2321		file, err := os.Open(name)2322		if err != nil {2323			closeFiles(files)2324			panic(err)2325		}2326		images = append(images, openai.File(file, name, "image/png"))2327		files = append(files, file)2328	}2329	return images, func() { closeFiles(files) }2330}23312332func closeFiles(files []*os.File) {2333	for _, file := range files {2334		if err := file.Close(); err != nil {2335			panic(err)2336		}2337	}2338}23392340func saveImage(filename, encoded string) {2341	image, err := base64.StdEncoding.DecodeString(encoded)2342	if err != nil {2343		panic(err)2344	}2345	if err := os.WriteFile(filename, image, 0o600); err != nil {2346		panic(err)2347	}2348}2349```23502351```java2352import com.openai.client.OpenAIClient;2353import com.openai.client.okhttp.OpenAIOkHttpClient;2354import com.openai.core.MultipartField;2355import com.openai.models.images.ImageEditParams;2356import java.io.IOException;2357import java.io.InputStream;2358import java.nio.file.Files;2359import java.nio.file.Path;2360import java.util.Base64;2361import java.util.List;23622363Path lotion = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH"));2364Path soap = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_2"));2365Path bathBomb = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_3"));2366Path incense = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_4"));2367try (InputStream lotionImage = Files.newInputStream(lotion);2368    InputStream bathBombImage = Files.newInputStream(bathBomb);2369    InputStream incenseImage = Files.newInputStream(incense);2370    InputStream soapImage = Files.newInputStream(soap)) {2371  var images =2372      client2373          .images()2374          .edit(2375              ImageEditParams.builder()2376                  .model("gpt-image-2.5-sunburst")2377                  .image(2378                      MultipartField.<ImageEditParams.Image>builder()2379                          .value(2380                              ImageEditParams.Image.ofInputStreams(2381                                  List.of(lotionImage, bathBombImage, incenseImage, soapImage)))2382                          .contentType("image/png")2383                          .filename("gift-basket-reference.png")2384                          .build())2385                  .prompt(2386                      """2387                      Generate a photorealistic image of a gift basket on a white background2388                      labeled 'Relax & Unwind' with a ribbon and handwriting-like font,2389                      containing all the items in the reference pictures.2390                      """)2391                  .build());23922393  Files.write(2394      Path.of("gift-basket.png"),2395      Base64.getDecoder().decode(images.data().orElseThrow().get(0).b64Json().orElseThrow()));2396}2397```23982399```ruby2400require "base64"2401require "openai"2402require "pathname"24032404client = OpenAI::Client.new2405images = %w[body-lotion.png bath-bomb.png incense-kit.png soap.png].map do |path|2406  Pathname(path)2407end2408result = client.images.edit(2409  image: images,2410  model: "gpt-image-2.5-sunburst",2411  prompt: <<~PROMPT2412    Generate a photorealistic image of a gift basket on a white background2413    labeled 'Relax & Unwind' with a ribbon and handwriting-like font,2414    containing all the items in the reference pictures.2415  PROMPT2416)2417generated_image = result.data&.first or raise "No image returned"2418File.binwrite("gift-basket.png", Base64.strict_decode64(generated_image.b64_json))2419```24202421```bash2422curl -s -D >(grep -i x-request-id >&2) \2423  -o >(jq -r '.data[0].b64_json' | base64 --decode > gift-basket.png) \2424  -X POST "https://api.openai.com/v1/images/edits" \2425  -H "Authorization: Bearer $OPENAI_API_KEY" \2426  -F "model=gpt-image-2.5-sunburst" \2427  -F "image[]=@body-lotion.png" \2428  -F "image[]=@bath-bomb.png" \2429  -F "image[]=@incense-kit.png" \2430  -F "image[]=@soap.png" \2431  -F 'prompt=Generate a photorealistic image of a gift basket on a white background labeled "Relax & Unwind" with a ribbon and handwriting-like font, containing all the items in the reference pictures'2432```24332434```bash2435openai images edit \2436  --model gpt-image-2.5-sunburst \2437  --image body-lotion.png \2438  --image bath-bomb.png \2439  --image incense-kit.png \2440  --image soap.png \2441  --prompt 'Generate a photorealistic image of a gift basket on a white background labeled "Relax & Unwind" with a ribbon and handwriting-like font, containing all the items in the reference pictures' \2442  --raw-output \2443  --transform 'data.0.b64_json' | base64 --decode > gift-basket.png2444```2445244624472448### Edit an image using a mask24492450You can provide a mask to indicate which part of the image should be edited.24512452When using a mask with GPT Image, additional instructions are sent to the model to help guide the editing process accordingly.24532454Masking with GPT Image is entirely prompt-based. The model uses the mask as2455  guidance, but may not follow its exact shape with complete precision.24562457If you provide multiple input images, the mask will be applied to the first image.2458245924602461Responses API24622463    Edit an image with a mask24642465```javascript2466import fs from "fs";2467import OpenAI from "openai";24682469const openai = new OpenAI();24702471async function createFile(filePath) {2472  const result = await openai.files.create({2473    file: fs.createReadStream(filePath),2474    purpose: "vision",2475  });2476  return result.id;2477}24782479const fileId = await createFile("fixtures/sunlit_lounge.png");2480const maskId = await createFile("fixtures/mask.png");24812482const response = await openai.responses.create({2483  model: "gpt-6-astra",2484  input: [2485    {2486      role: "user",2487      content: [2488        {2489          type: "input_text",2490          text: "generate an image of the same sunlit indoor lounge area with a pool but the pool should contain a flamingo",2491        },2492        {2493          type: "input_image",2494          file_id: fileId,2495          detail: "auto",2496        },2497      ],2498    },2499  ],2500  tools: [2501    {2502      type: "image_generation",2503      model: "gpt-image-2.5-sunburst",2504      quality: "high",2505      input_image_mask: {2506        file_id: maskId,2507      },2508    },2509  ],2510});25112512const imageData = response.output2513  .filter((output) => output.type === "image_generation_call")2514  .map((output) => output.result);25152516if (imageData.length > 0) {2517  const imageBase64 = imageData[0];2518  fs.writeFileSync("lounge.png", Buffer.from(imageBase64, "base64"));2519}2520```25212522```python2523from openai import OpenAI2524import base6425252526client = OpenAI()252725282529def create_file(file_path):2530    with open(file_path, "rb") as file_content:2531        result = client.files.create(file=file_content, purpose="vision")2532    return result.id253325342535fileId = create_file("sunlit_lounge.png")2536maskId = create_file("mask.png")25372538response = client.responses.create(2539    model="gpt-6-astra",2540    input=[2541        {2542            "role": "user",2543            "content": [2544                {2545                    "type": "input_text",2546                    "text": "generate an image of the same sunlit indoor lounge area with a pool but the pool should contain a flamingo",2547                },2548                {2549                    "type": "input_image",2550                    "file_id": fileId,2551                },2552            ],2553        },2554    ],2555    tools=[2556        {2557            "type": "image_generation",2558            "model": "gpt-image-2.5-sunburst",2559            "quality": "high",2560            "input_image_mask": {2561                "file_id": maskId,2562            },2563        },2564    ],2565)25662567image_data = [2568    output.result2569    for output in response.output2570    if output.type == "image_generation_call"2571]25722573if image_data:2574    image_base64 = image_data[0]2575    with open("lounge.png", "wb") as f:2576        f.write(base64.b64decode(image_base64))2577```25782579```go2580package main25812582import (2583	"context"2584	"encoding/base64"2585	"os"25862587	"github.com/openai/openai-go/v3"2588	"github.com/openai/openai-go/v3/responses"2589)25902591func main() {2592	client := openai.NewClient()2593	imageID := uploadImage(client, "sunlit_lounge.png")2594	maskID := uploadImage(client, "mask.png")2595	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{2596		Model: "gpt-6-astra",2597		Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{2598			responses.ResponseInputItemParamOfMessage(2599				responses.ResponseInputMessageContentListParam{2600					responses.ResponseInputContentParamOfInputText("Generate an image of the same sunlit indoor lounge area with a pool, but the pool should contain a flamingo."),2601					{OfInputImage: &responses.ResponseInputImageParam{FileID: openai.String(imageID), Detail: responses.ResponseInputImageDetailAuto}},2602				},2603				responses.EasyInputMessageRoleUser,2604			),2605		}},2606		Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{2607			Model:          "gpt-image-2.5-sunburst",2608			Quality:        "high",2609			InputImageMask: responses.ToolImageGenerationInputImageMaskParam{FileID: openai.String(maskID)},2610		}}},2611	})2612	if err != nil {2613		panic(err)2614	}2615	saveFirstGeneratedImage(response, "lounge.png")2616}26172618func uploadImage(client openai.Client, filename string) string {2619	file, err := os.Open(filename)2620	if err != nil {2621		panic(err)2622	}2623	defer file.Close()2624	uploaded, err := client.Files.New(context.Background(), openai.FileNewParams{File: file, Purpose: openai.FilePurposeVision})2625	if err != nil {2626		panic(err)2627	}2628	return uploaded.ID2629}26302631func saveFirstGeneratedImage(response *responses.Response, filename string) {2632	for _, output := range response.Output {2633		if output.Type != "image_generation_call" {2634			continue2635		}2636		image, err := base64.StdEncoding.DecodeString(output.AsImageGenerationCall().Result)2637		if err != nil {2638			panic(err)2639		}2640		if err := os.WriteFile(filename, image, 0o600); err != nil {2641			panic(err)2642		}2643		return2644	}2645	panic("response did not include an image generation call")2646}2647```26482649```java2650import com.openai.client.OpenAIClient;2651import com.openai.client.okhttp.OpenAIOkHttpClient;2652import com.openai.models.files.FileCreateParams;2653import com.openai.models.files.FilePurpose;2654import com.openai.models.responses.ResponseCreateParams;2655import com.openai.models.responses.ResponseInputImage;2656import com.openai.models.responses.ResponseInputItem;2657import com.openai.models.responses.Tool;2658import java.io.IOException;2659import java.nio.file.Files;2660import java.nio.file.Path;2661import java.util.Base64;2662import java.util.List;26632664var image =2665    client2666        .files()2667        .create(2668            FileCreateParams.builder()2669                .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))2670                .purpose(FilePurpose.VISION)2671                .build());26722673var mask =2674    client2675        .files()2676        .create(2677            FileCreateParams.builder()2678                .file(Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_MASK_PATH")))2679                .purpose(FilePurpose.VISION)2680                .build());26812682var response =2683    client2684        .responses()2685        .create(2686            ResponseCreateParams.builder()2687                .model("gpt-6-astra")2688                .inputOfResponse(2689                    List.of(2690                        ResponseInputItem.ofMessage(2691                            ResponseInputItem.Message.builder()2692                                .role(ResponseInputItem.Message.Role.USER)2693                                .addInputTextContent("Add a flamingo to the pool.")2694                                .addContent(2695                                    ResponseInputImage.builder()2696                                        .detail(ResponseInputImage.Detail.AUTO)2697                                        .fileId(image.id())2698                                        .build())2699                                .build())))2700                .addTool(2701                    Tool.ImageGeneration.builder()2702                        .inputImageMask(2703                            Tool.ImageGeneration.InputImageMask.builder()2704                                .fileId(mask.id())2705                                .build())2706                        .build())2707                .build());27082709String imageResult =2710    response.output().stream()2711        .flatMap(item -> item.imageGenerationCall().stream())2712        .flatMap(call -> call.result().stream())2713        .findFirst()2714        .orElseThrow(() -> new IllegalStateException("No generated image returned"));2715Files.write(Path.of("lounge.png"), Base64.getDecoder().decode(imageResult));2716```27172718```ruby2719require "base64"2720require "openai"2721require "pathname"27222723client = OpenAI::Client.new2724image = client.files.create(file: Pathname("sunlit_lounge.png"), purpose: :vision)2725mask = client.files.create(file: Pathname("mask.png"), purpose: :vision)2726response = client.responses.create(2727  model: "gpt-6-astra",2728  input: [2729    {2730      role: :user,2731      content: [2732        {2733          type: :input_text,2734          text: "Add a flamingo to the pool."2735        },2736        {2737          type: :input_image,2738          file_id: image.id2739        }2740      ]2741    }2742  ],2743  tools: [2744    {2745      type: :image_generation,2746      model: "gpt-image-2.5-sunburst",2747      input_image_mask: { file_id: mask.id }2748    }2749  ]2750)27512752image_call = response.output.find do |item|2753  item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)2754end2755unless image_call.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)2756  raise "No image generation call returned"2757end27582759File.binwrite("lounge.png", Base64.strict_decode64(image_call.result))2760```27612762  27632764  27652766    2767Image API27682769    Edit an image with a mask27702771```javascript2772import fs from "fs";2773import OpenAI, { toFile } from "openai";27742775const client = new OpenAI();27762777const rsp = await client.images.edit({2778  model: "gpt-image-2.5-sunburst",2779  image: await toFile(fs.createReadStream("fixtures/sunlit_lounge.png"), null, {2780    type: "image/png",2781  }),2782  mask: await toFile(fs.createReadStream("fixtures/mask.png"), null, {2783    type: "image/png",2784  }),2785  prompt: "A sunlit indoor lounge area with a pool containing a flamingo",2786});27872788// Save the image to a file2789const image_base64 = rsp.data[0].b64_json;2790const image_bytes = Buffer.from(image_base64, "base64");2791fs.writeFileSync("lounge.png", image_bytes);2792```27932794```python2795from openai import OpenAI2796import base6427972798client = OpenAI()27992800result = client.images.edit(2801    model="gpt-image-2.5-sunburst",2802    image=open("sunlit_lounge.png", "rb"),2803    mask=open("mask.png", "rb"),2804    prompt="A sunlit indoor lounge area with a pool containing a flamingo",2805)28062807image_base64 = result.data[0].b64_json2808image_bytes = base64.b64decode(image_base64)28092810# Save the image to a file2811with open("composition.png", "wb") as f:2812    f.write(image_bytes)2813```28142815```go2816package main28172818import (2819	"context"2820	"encoding/base64"2821	"os"28222823	"github.com/openai/openai-go/v3"2824)28252826func main() {2827	client := openai.NewClient()2828	image, err := os.Open("sunlit_lounge.png")2829	if err != nil {2830		panic(err)2831	}2832	defer image.Close()2833	mask, err := os.Open("mask.png")2834	if err != nil {2835		panic(err)2836	}2837	defer mask.Close()28382839	response, err := client.Images.Edit(context.Background(), openai.ImageEditParams{2840		Model:  openai.ImageModel("gpt-image-2.5-sunburst"),2841		Image:  openai.ImageEditParamsImageUnion{OfFile: openai.File(image, "sunlit_lounge.png", "image/png")},2842		Mask:   openai.File(mask, "mask.png", "image/png"),2843		Prompt: "A sunlit indoor lounge area with a pool containing a flamingo",2844	})2845	if err != nil {2846		panic(err)2847	}2848	result, err := base64.StdEncoding.DecodeString(response.Data[0].B64JSON)2849	if err != nil {2850		panic(err)2851	}2852	if err := os.WriteFile("lounge.png", result, 0o600); err != nil {2853		panic(err)2854	}2855}2856```28572858```java2859import com.openai.client.OpenAIClient;2860import com.openai.client.okhttp.OpenAIOkHttpClient;2861import com.openai.core.MultipartField;2862import com.openai.models.images.ImageEditParams;2863import java.io.IOException;2864import java.io.InputStream;2865import java.nio.file.Files;2866import java.nio.file.Path;2867import java.util.Base64;28682869Path imagePath = Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH"));2870Path maskPath = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_MASK_PATH"));2871try (InputStream image = Files.newInputStream(imagePath);2872    InputStream mask = Files.newInputStream(maskPath)) {2873  var images =2874      client2875          .images()2876          .edit(2877              ImageEditParams.builder()2878                  .model("gpt-image-2.5-sunburst")2879                  .image(2880                      MultipartField.<ImageEditParams.Image>builder()2881                          .value(ImageEditParams.Image.ofInputStream(image))2882                          .contentType("image/png")2883                          .filename(imagePath.getFileName().toString())2884                          .build())2885                  .prompt("A sunlit indoor lounge area with a pool containing a flamingo")2886                  .mask(2887                      MultipartField.<InputStream>builder()2888                          .value(mask)2889                          .contentType("image/png")2890                          .filename(maskPath.getFileName().toString())2891                          .build())2892                  .build());28932894  Files.write(2895      Path.of("lounge.png"),2896      Base64.getDecoder().decode(images.data().orElseThrow().get(0).b64Json().orElseThrow()));2897}2898```28992900```ruby2901require "openai"2902require "pathname"2903require "base64"29042905client = OpenAI::Client.new2906image = Pathname("sunlit_lounge.png")2907mask = Pathname("mask.png")2908result = client.images.edit(2909  image: image,2910  mask: mask,2911  model: "gpt-image-2.5-sunburst",2912  prompt: "A sunlit indoor lounge area with a pool containing a flamingo"2913)2914generated_image = result.data&.first or raise "No image returned"2915File.binwrite("lounge.png", Base64.strict_decode64(generated_image.b64_json))2916```29172918```bash2919curl -s -D >(grep -i x-request-id >&2) \2920  -o >(jq -r '.data[0].b64_json' | base64 --decode > lounge.png) \2921  -X POST "https://api.openai.com/v1/images/edits" \2922  -H "Authorization: Bearer $OPENAI_API_KEY" \2923  -F "model=gpt-image-2.5-sunburst" \2924  -F "mask=@mask.png" \2925  -F "image[]=@sunlit_lounge.png" \2926  -F 'prompt=A sunlit indoor lounge area with a pool containing a flamingo'2927```29282929```bash2930openai images edit \2931  --model gpt-image-2.5-sunburst \2932  --image sunlit_lounge.png \2933  --mask mask.png \2934  --prompt "A sunlit indoor lounge area with a pool containing a flamingo" \2935  --raw-output \2936  --transform 'data.0.b64_json' | base64 --decode > out.png2937```2938293929402941294229432944| Image                                                                                                                                 | Mask                                                                                                                            | Output                                                                                                                                                                  |2945| ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |2946| <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/sunlit_lounge.png" alt="A pink room with a pool" /> | <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/mask.png" alt="A mask in part of the pool" /> | <img className="images-example-image" src="https://developers.openai.com/images/image-25-article/sunlit_lounge_result.png" alt="The original pool with an inflatable flamingo replacing the mask" /> |2947294829492950295129522953  Prompt: a sunlit indoor lounge area with a pool containing a flamingo2954295529562957#### Mask requirements29582959The image to edit and mask must be of the same format and size (less than 50MB in size).29602961The mask image must also contain an alpha channel. If you're using an image editing tool to create the mask, make sure to save the mask with an alpha channel.29622963You can modify a black and white image programmatically to add an alpha channel.29642965Add an alpha channel to a black and white mask29662967```python2968from PIL import Image2969from io import BytesIO29702971# 1. Load your black & white mask as a grayscale image2972mask = Image.open("mask.png").convert("L")29732974# 2. Convert it to RGBA so it has space for an alpha channel2975mask_rgba = mask.convert("RGBA")29762977# 3. Then use the mask itself to fill that alpha channel2978mask_rgba.putalpha(mask)29792980# 4. Convert the mask into bytes2981buf = BytesIO()2982mask_rgba.save(buf, format="PNG")2983mask_bytes = buf.getvalue()29842985# 5. Save the resulting file2986img_path_mask_alpha = "mask_alpha.png"2987with open(img_path_mask_alpha, "wb") as f:2988    f.write(mask_bytes)2989```29902991```go2992package main29932994import (2995	"image"2996	"image/color"2997	"image/png"2998	"os"2999)30003001func main() {3002	file, err := os.Open("mask.png")3003	if err != nil {3004		panic(err)3005	}3006	defer file.Close()30073008	mask, _, err := image.Decode(file)3009	if err != nil {3010		panic(err)3011	}3012	bounds := mask.Bounds()3013	withAlpha := image.NewNRGBA(bounds)3014	for y := bounds.Min.Y; y < bounds.Max.Y; y++ {3015		for x := bounds.Min.X; x < bounds.Max.X; x++ {3016			gray := color.GrayModel.Convert(mask.At(x, y)).(color.Gray)3017			withAlpha.SetNRGBA(x, y, color.NRGBA{R: gray.Y, G: gray.Y, B: gray.Y, A: gray.Y})3018		}3019	}30203021	output, err := os.Create("mask_alpha.png")3022	if err != nil {3023		panic(err)3024	}3025	if err := png.Encode(output, withAlpha); err != nil {3026		panic(err)3027	}3028	if err := output.Close(); err != nil {3029		panic(err)3030	}3031}3032```303330343035## Customize Image Output30363037You can configure the following output options:30383039- **Size**: Image dimensions (for example, `1024x1024`, `1024x1536`)3040- **Quality**: Rendering quality (for example, `low`, `medium`, `high`)3041- **Format**: File output format3042- **Compression**: Compression level (0-100%) for JPEG and WebP formats3043- **Background**: Transparent, opaque, or automatic30443045`size`, `quality`, and `background` support the `auto` option, where the model will automatically select the best option based on the prompt.30463047### Size and quality options30483049`gpt-image-2.5-sunburst` and `gpt-image-2.5-flare` add `xhigh` and `max` quality settings. Both default to `auto`. Earlier GPT Image models support quality settings up to `high`.30503051| Setting           | Options                                                               |3052| ----------------- | --------------------------------------------------------------------- |3053| Recommended sizes | `1024x1024` (square), `1536x1024` (landscape), `1024x1536` (portrait) |3054| Quality           | `low`, `medium`, `high`, `xhigh`, `max`, `auto`                       |30553056Both models also support custom dimensions as `WIDTHxHEIGHT` strings, such as `1536x864`. Width and height must be multiples of 16, the aspect ratio must be between 1:3 and 3:1, and neither edge may exceed 3840 pixels. The total pixel count must be between 655,360 and 8,294,400 (4K). Resolutions above `2560x1440` are experimental.30573058For transparent backgrounds with either model, set `background: "transparent"` and use `output_format: "png"` or `"webp"`.30593060Use `quality: "low"` for quick drafts. For final assets, compare higher quality settings to find the right balance of detail, latency, and cost.30613062### Output format30633064The Image API returns base64-encoded image data.3065The default format is `png`, but you can also request `jpeg` or `webp`.30663067If using `jpeg` or `webp`, you can also specify the `output_compression` parameter to control the compression level (0-100%). For example, `output_compression=50` will compress the image by 50%.30683069Using `jpeg` is faster than `png`, so you should prioritize this format if3070  latency is a concern.30713072## Limitations30733074GPT Image models are powerful and versatile image generation models, but they still have some limitations to be aware of:30753076- **Latency:** Complex prompts may take up to 2 minutes to process.3077- **Text Rendering:** Although significantly improved, the model can still struggle with precise text placement and clarity.3078- **Consistency:** While capable of producing consistent imagery, the model may occasionally struggle to maintain visual consistency for recurring characters or brand elements across multiple generations.3079- **Composition Control:** Despite improved instruction following, the model may have difficulty placing elements precisely in structured or layout-sensitive compositions.30803081### Content Moderation30823083All prompts and generated images are filtered in accordance with our [content policy](https://openai.com/policies/usage-policies/).30843085For image generation using GPT Image models, you can control moderation strictness with the `moderation` parameter. This parameter supports two values:30863087- `auto` (default): Standard filtering that seeks to limit creating certain categories of potentially age-inappropriate content.3088- `low`: Less restrictive filtering.30893090### Handling blocked requests and other errors30913092Handle image generation failures the same way you handle other API errors: check the HTTP status or SDK exception type, log the request ID, and refer to the [error codes guide](https://developers.openai.com/api/docs/guides/error-codes) for authentication, quota, rate-limit, and server failures. Retry transient rate-limit and server failures with backoff. Don't automatically retry quota errors or image generation user errors that require changing the request.30933094Some image generation failures are user-correctable and may return `error.type = "image_generation_user_error"`. Don't automatically retry these errors without modifying the prompt or input images. For programmatic handling, use `error.code` as the stable discriminator.30953096When `error.code = "moderation_blocked"`, the error may also include an optional `error.moderation_details` object:30973098```json3099{3100  "error": {3101    "type": "image_generation_user_error",3102    "code": "moderation_blocked",3103    "moderation_details": {3104      "moderation_stage": "input",3105      "categories": ["harassment"]3106    }3107  }3108}3109```31103111The `moderation_details` object provides coarse debugging context without exposing internal classifier labels or scores.31123113`moderation_stage` can be:31143115- `input`: The block came from the prompt or request inputs.3116- `output`: The block came from a generated image or downstream output moderation stage.3117- `unknown`: A rare fallback when provenance is hard to determine.31183119`categories` contains coarse public labels. For example, you might see values like `harassment`, `self-harm`, `sexual`, or `violence`.31203121For most apps, keep the primary end-user message generic. Use `moderation_details` for developer logs, support workflows, analytics, and light remediation hints.31223123Handle moderation-blocked image generation errors31243125```javascript3126import OpenAI from "openai";31273128const openai = new OpenAI();31293130try {3131  // The same error handling pattern applies to image generation requests,3132  // image edits, and Responses API tool calls that generate images.3133  await openai.images.generate({3134    model: "gpt-image-2.5-sunburst",3135    prompt: "Create a poster humiliating my coworker with insulting captions",3136  });3137} catch (error) {3138  if (error?.code !== "moderation_blocked") {3139    throw error;3140  }31413142  const moderationDetails = error.error?.moderation_details;3143  const categories = moderationDetails?.categories ?? [];3144  const stage = moderationDetails?.moderation_stage;31453146  let hint =3147    "This request could not be completed because it did not meet safety requirements.";31483149  if (categories.includes("harassment")) {3150    hint =3151      "Try removing abusive or targeting language and focus on neutral visual details instead.";3152  } else if (stage === "input") {3153    hint =3154      "Try revising the prompt or input images and submit the request again.";3155  } else if (stage === "output") {3156    hint =3157      "The generated result was blocked by a safety check. Try changing the prompt and generating again.";3158  }31593160  console.error("Image generation blocked", {3161    request_id: error?.requestID,3162    code: error?.code,3163    moderation_details: moderationDetails,3164  });31653166  console.log(hint);3167}3168```31693170```python3171import openai3172from openai import OpenAI31733174client = OpenAI()31753176try:3177    # The same error handling pattern applies to image generation requests,3178    # image edits, and Responses API tool calls that generate images.3179    client.images.generate(3180        model="gpt-image-2.5-sunburst",3181        prompt="Create a poster humiliating my coworker with insulting captions",3182    )3183except openai.BadRequestError as error:3184    if error.code != "moderation_blocked":3185        raise31863187    error_body = error.body if isinstance(error.body, dict) else {}3188    moderation_details = error_body.get("moderation_details") or {}3189    categories = moderation_details.get("categories") or []3190    stage = moderation_details.get("moderation_stage")31913192    hint = "This request could not be completed because it did not meet safety requirements."31933194    if "harassment" in categories:3195        hint = "Try removing abusive or targeting language and focus on neutral visual details instead."3196    elif stage == "input":3197        hint = "Try revising the prompt or input images and submit the request again."3198    elif stage == "output":3199        hint = "The generated result was blocked by a safety check. Try changing the prompt and generating again."32003201    print(3202        "Image generation blocked",3203        {3204            "request_id": error.request_id,3205            "code": error.code,3206            "moderation_details": moderation_details,3207        },3208    )32093210    print(hint)3211```32123213```go3214package main32153216import (3217	"context"3218	"encoding/json"3219	"errors"3220	"fmt"3221	"slices"32223223	"github.com/openai/openai-go/v3"3224)32253226func main() {3227	client := openai.NewClient()3228	_, err := client.Images.Generate(context.Background(), openai.ImageGenerateParams{3229		Model:  openai.ImageModel("gpt-image-2.5-sunburst"),3230		Prompt: "Create a poster humiliating my coworker with insulting captions",3231	})3232	if err == nil {3233		return3234	}32353236	var apiError *openai.Error3237	if !errors.As(err, &apiError) || apiError.Code != "moderation_blocked" {3238		panic(err)3239	}32403241	var body struct {3242		ModerationDetails struct {3243			Categories      []string `json:"categories"`3244			ModerationStage string   `json:"moderation_stage"`3245		} `json:"moderation_details"`3246	}3247	if err := json.Unmarshal([]byte(apiError.RawJSON()), &body); err != nil {3248		panic(err)3249	}32503251	hint := "This request could not be completed because it did not meet safety requirements."3252	if slices.Contains(body.ModerationDetails.Categories, "harassment") {3253		hint = "Try removing abusive or targeting language and focus on neutral visual details instead."3254	} else if body.ModerationDetails.ModerationStage == "input" {3255		hint = "Try revising the prompt or input images and submit the request again."3256	} else if body.ModerationDetails.ModerationStage == "output" {3257		hint = "The generated result was blocked by a safety check. Try changing the prompt and generating again."3258	}32593260	fmt.Printf("Image generation blocked (%s): %s\n", apiError.Code, hint)3261}3262```32633264```java3265import com.openai.client.OpenAIClient;3266import com.openai.client.okhttp.OpenAIOkHttpClient;3267import com.openai.errors.BadRequestException;3268import com.openai.models.images.ImageGenerateParams;3269import java.util.List;3270import java.util.Map;32713272try {3273  var images =3274      client3275          .images()3276          .generate(3277              ImageGenerateParams.builder()3278                  .model("gpt-image-2.5-sunburst")3279                  .prompt("Create a poster humiliating my coworker with insulting captions")3280                  .build());32813282  System.out.println(images.data().orElseThrow().get(0).b64Json().orElseThrow());3283} catch (BadRequestException error) {3284  if (!error.code().orElse("").equals("moderation_blocked")) {3285    throw error;3286  }3287  Map<?, ?> body = error.body().convert(Map.class);3288  Object detailsValue = body.get("moderation_details");3289  Map<?, ?> details = detailsValue instanceof Map<?, ?> values ? values : Map.of();3290  Object categories = details.get("categories");3291  Object stage = details.get("moderation_stage");32923293  String hint = "This request did not meet safety requirements.";3294  if (categories instanceof List<?> values && values.contains("harassment")) {3295    hint = "Remove abusive or targeting language and focus on neutral visual details.";3296  } else if ("input".equals(stage)) {3297    hint = "Revise the prompt or input images, then submit the request again.";3298  } else if ("output".equals(stage)) {3299    hint = "Change the prompt and generate again; the generated result was blocked.";3300  }3301  System.err.println("Image generation blocked (" + error.code().orElseThrow() + "): " + hint);3302}3303```33043305```ruby3306require "openai"33073308client = OpenAI::Client.new3309begin3310  client.images.generate(3311    model: "gpt-image-2.5-sunburst",3312    prompt: "Create a poster humiliating my coworker with insulting captions"3313  )3314rescue OpenAI::Errors::BadRequestError => error3315  raise unless error.code == "moderation_blocked"33163317  body = Hash.try_convert(error.body) || {}3318  moderation_details = body[:moderation_details] || body["moderation_details"] || {}3319  categories = moderation_details[:categories] || moderation_details["categories"] || []3320  stage = moderation_details[:moderation_stage] || moderation_details["moderation_stage"]33213322  hint = "This request did not meet safety requirements."3323  if categories.include?("harassment")3324    hint = "Remove abusive or targeting language and focus on neutral visual details."3325  elsif stage == "input"3326    hint = "Revise the prompt or input images, then submit the request again."3327  elsif stage == "output"3328    hint = "Change the prompt and generate again; the generated result was blocked."3329  end33303331  warn("Image generation blocked (#{error.code}): #{hint}")3332end3333```333433353336### Supported models33373338When using image generation in the Responses API, `gpt-5` and newer models should support the image generation tool. [Check the model detail page for your model](https://developers.openai.com/api/docs/models) to confirm if your desired model can use the image generation tool.33393340## Cost and latency33413342### GPT Image 2.5 costs33433344Responses API requests include the mainline model's token usage in addition to image generation costs.33453346Both GPT Image 2.5 models use the same token rates: $8 per million image input tokens, $2 per million cached image input tokens, $30 per million image output tokens, $5 per million text input tokens, and $1.25 per million cached text input tokens. See [pricing](https://developers.openai.com/api/docs/pricing#image-generation).33473348Use the response's `usage` to measure token consumption for your prompts, sizes, and quality settings. Equal token rates don't mean equal cost per image: token consumption can differ by model and quality setting. For older-model pricing examples, see [Earlier GPT Image models](#earlier-gpt-image-models).33493350335133523353### GPT Image 2.5 and GPT Image 2 output tokens33543355Select a model, quality, and size to estimate output tokens and image output cost.3356For `gpt-image-2.5-sunburst` and `gpt-image-2.5-flare`, the quality options are `low`, `medium`, `high`, `xhigh`, and `max`.3357For `gpt-image-2`, the options are `low`, `medium`, and `high`.3358The models can use different token counts for the same quality setting and share the same price per image output token.3359Use explicit quality and size values for this estimate; `auto` depends on the generated image.33603361<GptImageTokenCalculator3362  client:load3363  outputPricePerMillion={Number(3364    pricing.latest.subsections3365      .find((section) => section.price_type === "Image tokens")3366      ?.items.find((item) => item.name === "gpt-image-2")?.values.main.output3367  )}3368/>33693370### Partial images cost33713372If you want to [stream image generation](#streaming) using the `partial_images` parameter, each partial image will incur an additional 100 image output tokens.33733374## Earlier GPT Image models33753376The details below apply to earlier models, not Sunburst or Flare. For new integrations, use one of the GPT Image 2.5 models described above.33773378<details>3379<summary>GPT Image 2 settings and input fidelity</summary>33803381`gpt-image-2` accepts any resolution in the `size` parameter when it satisfies the constraints below. Square images are typically fastest to generate.33823383<table>3384  <tbody>3385    <tr>3386      <td>Popular sizes</td>3387      <td>3388        <ul>3389          <li>3390            `1024x1024` (square)3391          </li>3392          <li>3393            `1536x1024` (landscape)3394          </li>3395          <li>3396            `1024x1536` (portrait)3397          </li>3398          <li>3399            `2048x2048` (2K square)3400          </li>3401          <li>3402            `2048x1152` (2K landscape)3403          </li>3404          <li>3405            `3840x2160` (4K landscape)3406          </li>3407          <li>3408            `2160x3840` (4K portrait)3409          </li>3410          <li>3411            `auto` (default)3412          </li>3413        </ul>3414      </td>3415    </tr>3416    <tr>3417      <td>Size constraints</td>3418      <td>3419        <ul>3420          <li>3421            Maximum edge length must be less than or equal to 3422            `3840px`3423          </li>3424          <li>3425            Both edges must be multiples of `16px`3426          </li>3427          <li>3428            Long edge to short edge ratio must not exceed `3:1`3429          </li>3430          <li>3431            Total pixels must be at least `655,360` and no more than 3432            `8,294,400`3433          </li>3434        </ul>3435      </td>3436    </tr>3437    <tr>3438      <td>Quality options</td>3439      <td>3440        <ul>3441          <li>3442            `low`3443          </li>3444          <li>3445            `medium`3446          </li>3447          <li>3448            `high`3449          </li>3450          <li>3451            `auto` (default)3452          </li>3453        </ul>3454      </td>3455    </tr>3456  </tbody>3457</table>34583459### Image input fidelity34603461The `input_fidelity` parameter controls how strongly a model preserves details from input images during edits and reference-image workflows. For `gpt-image-2`, omit this parameter; the API doesn't allow changing it because the model processes every image input at high fidelity automatically.34623463Because `gpt-image-2` always processes image inputs at high fidelity, image3464  input tokens can be higher for edit requests that include reference images. To3465  understand the cost implications, refer to the [vision3466  costs](https://developers.openai.com/api/docs/guides/images-vision?api-mode=responses#calculating-costs)3467  section.34683469</details>34703471<details>3472<summary>Older-model pricing examples</summary>34733474### Models prior to `gpt-image-2`34753476GPT Image models prior to `gpt-image-2` generate images by first producing specialized image tokens. Both latency and eventual cost are proportional to the number of tokens required to render an image—larger image sizes and higher quality settings result in more tokens.34773478The number of tokens generated depends on image dimensions and quality:34793480| Quality | Square (1024×1024) | Portrait (1024×1536) | Landscape (1536×1024) |3481| ------- | ------------------ | -------------------- | --------------------- |3482| Low     | 272 tokens         | 408 tokens           | 400 tokens            |3483| Medium  | 1056 tokens        | 1584 tokens          | 1568 tokens           |3484| High    | 4160 tokens        | 6240 tokens          | 6208 tokens           |34853486Note that you will also need to account for [input tokens](https://developers.openai.com/api/docs/guides/images-vision?api-mode=responses#calculating-costs): text tokens for the prompt and image tokens for the input images if editing images.3487Because `gpt-image-2` always processes image inputs at high fidelity, edit requests that include reference images can use more input tokens.34883489Refer to the [pricing page](https://developers.openai.com/api/docs/pricing#image-generation) for current3490text and image token prices, and use the [Calculating costs](#calculating-costs)3491section below to estimate request costs.34923493The final cost is the sum of:34943495- input text tokens3496- input image tokens if using the edits endpoint3497- image output tokens34983499### Calculating costs35003501Use the pricing calculator below to estimate request costs for GPT Image models.3502`gpt-image-2` supports thousands of valid resolutions; the table below lists the3503same sizes used for previous GPT Image models for comparison. For GPT Image 1.5,3504GPT Image 1, and GPT Image 1 Mini, the legacy per-image output pricing table is3505also listed below. You should still account for text and image input tokens when3506estimating the total cost of a request.35073508A larger non-square resolution can sometimes produce fewer output tokens than3509  a smaller or square resolution at the same quality setting.35103511<table3512  style={{ borderCollapse: "collapse", tableLayout: "fixed", width: "100%" }}3513>3514  <thead>3515    <tr>3516      <th style={{ textAlign: "left", padding: "8px", width: "28%" }}>Model</th>3517      <th style={{ textAlign: "left", padding: "8px", width: "14%" }}>3518        Quality3519      </th>3520      <th style={{ padding: "8px", width: "19.33%" }}>1024 x 1024</th>3521      <th style={{ padding: "8px", width: "19.33%" }}>1024 x 1536</th>3522      <th style={{ padding: "8px", width: "19.34%" }}>1536 x 1024</th>3523    </tr>3524  </thead>3525  <tbody>3526    <tr>3527      <td rowSpan="3" style={{ padding: "8px", width: "28%" }}>3528        GPT Image 23529        35303531        3532Additional sizes available35333534      </td>3535      <td style={{ padding: "8px" }}>Low</td>3536      <td style={{ padding: "8px" }}>$0.006</td>3537      <td style={{ padding: "8px" }}>$0.005</td>3538      <td style={{ padding: "8px" }}>$0.005</td>3539    </tr>3540    <tr>3541      <td style={{ padding: "8px" }}>Medium</td>3542      <td style={{ padding: "8px" }}>$0.053</td>3543      <td style={{ padding: "8px" }}>$0.041</td>3544      <td style={{ padding: "8px" }}>$0.041</td>3545    </tr>3546    <tr>3547      <td style={{ padding: "8px" }}>High</td>3548      <td style={{ padding: "8px" }}>$0.211</td>3549      <td style={{ padding: "8px" }}>$0.165</td>3550      <td style={{ padding: "8px" }}>$0.165</td>3551    </tr>35523553    <tr>3554      <td rowSpan="3" style={{ padding: "8px", width: "28%" }}>3555        GPT Image 1.53556      </td>3557      <td style={{ padding: "8px" }}>Low</td>3558      <td style={{ padding: "8px" }}>$0.009</td>3559      <td style={{ padding: "8px" }}>$0.013</td>3560      <td style={{ padding: "8px" }}>$0.013</td>3561    </tr>3562    <tr>3563      <td style={{ padding: "8px" }}>Medium</td>3564      <td style={{ padding: "8px" }}>$0.034</td>3565      <td style={{ padding: "8px" }}>$0.05</td>3566      <td style={{ padding: "8px" }}>$0.05</td>3567    </tr>3568    <tr>3569      <td style={{ padding: "8px" }}>High</td>3570      <td style={{ padding: "8px" }}>$0.133</td>3571      <td style={{ padding: "8px" }}>$0.2</td>3572      <td style={{ padding: "8px" }}>$0.2</td>3573    </tr>35743575    <tr>3576      <td rowSpan="3" style={{ padding: "8px", width: "28%" }}>3577        GPT Image 13578      </td>3579      <td style={{ padding: "8px" }}>Low</td>3580      <td style={{ padding: "8px" }}>$0.011</td>3581      <td style={{ padding: "8px" }}>$0.016</td>3582      <td style={{ padding: "8px" }}>$0.016</td>3583    </tr>3584    <tr>3585      <td style={{ padding: "8px" }}>Medium</td>3586      <td style={{ padding: "8px" }}>$0.042</td>3587      <td style={{ padding: "8px" }}>$0.063</td>3588      <td style={{ padding: "8px" }}>$0.063</td>3589    </tr>3590    <tr>3591      <td style={{ padding: "8px" }}>High</td>3592      <td style={{ padding: "8px" }}>$0.167</td>3593      <td style={{ padding: "8px" }}>$0.25</td>3594      <td style={{ padding: "8px" }}>$0.25</td>3595    </tr>35963597    <tr>3598      <td rowSpan="3" style={{ padding: "8px", width: "28%" }}>3599        GPT Image 1 Mini3600      </td>3601      <td style={{ padding: "8px" }}>Low</td>3602      <td style={{ padding: "8px" }}>$0.005</td>3603      <td style={{ padding: "8px" }}>$0.006</td>3604      <td style={{ padding: "8px" }}>$0.006</td>3605    </tr>3606    <tr>3607      <td style={{ padding: "8px" }}>Medium</td>3608      <td style={{ padding: "8px" }}>$0.011</td>3609      <td style={{ padding: "8px" }}>$0.015</td>3610      <td style={{ padding: "8px" }}>$0.015</td>3611    </tr>3612    <tr>3613      <td style={{ padding: "8px" }}>High</td>3614      <td style={{ padding: "8px" }}>$0.036</td>3615      <td style={{ padding: "8px" }}>$0.052</td>3616      <td style={{ padding: "8px" }}>$0.052</td>3617    </tr>36183619  </tbody>3620</table>36213622</details>
Files main
Menu

Theme