跳至主要内容

此浏览器不再受支持。

请升级到 Microsoft Edge 以使用最新的功能、安全更新和技术支持。

下载 Microsoft Edge 有关 Internet Explorer 和 Microsoft Edge 的详细信息
microsoft-foundry.rest.security.o-auth2-auth

Images

Create an image

POST /openai/v1/images/generations

Creates an image from the supplied request.

请求正文

The request body.

Content-Type: application/json
prompt string 必需

A text description of the desired image(s). The maximum length is 32000 characters.

model string | enum 必需

The GPT image model to use for image generation. Specify a model explicitly. Supported models include gpt-image-1, gpt-image-1-mini, gpt-image-1.5, gpt-image-2, gpt-image-2-2026-04-21, gpt-image-2.5-sunburst, gpt-image-2.5-sunburst-2026-09-08, gpt-image-2.5-flare, gpt-image-2.5-flare-2026-09-08, and chatgpt-image-latest.

以下任何项:
string
enum
gpt-image-1.5gpt-image-2gpt-image-2-2026-04-21gpt-image-2.5-sunburstgpt-image-2.5-sunburst-2026-09-08gpt-image-2.5-flaregpt-image-2.5-flare-2026-09-08gpt-image-1gpt-image-1-minichatgpt-image-latestdall-e-2dall-e-3
n integer | null

The number of images to generate. Must be between 1 and 10.

quality enum

The quality of the image that will be generated. - auto (default value) will automatically select the best quality for the given model. - high, medium and low are supported for the GPT image models. - gpt-image-2.5-sunburst and gpt-image-2.5-flare, including their 2026-09-08 snapshots, also support xhigh and max.

lowmediumhighxhighmaxautostandardhd
response_format enum

Legacy response format parameter for retired image models. Unsupported for GPT image models, which always return base64-encoded images.

urlb64_json
output_format enum

The format in which the generated images are returned. This parameter is only supported for the GPT image models. Must be one of png, jpeg, or webp.

pngjpegwebp
output_compression integer | null

The compression level (0-100%) for the generated images. This parameter is only supported for the GPT image models with the webp or jpeg output formats, and defaults to 100.

stream boolean | null

Generate the image in streaming mode. Defaults to false. See the Image generation guide for more information. This parameter is only supported for the GPT image models.

partial_images integer | null

The number of partial images to generate. This parameter is used for streaming responses that return partial images. Value must be between 0 and 3. When set to 0, the response will be a single image sent in one streaming event. Note that the final image may be sent before the full number of partial images are generated if the full image is generated more quickly.

size string | enum | null

The size of the generated images. For gpt-image-2, gpt-image-2-2026-04-21, gpt-image-2.5-sunburst, gpt-image-2.5-sunburst-2026-09-08, gpt-image-2.5-flare, and gpt-image-2.5-flare-2026-09-08, arbitrary resolutions are supported as WIDTHxHEIGHT strings, for example 1536x864. Width and height must both be divisible by 16 and the requested aspect ratio must be between 1:3 and 3:1. Resolutions above 2560x1440 are experimental, and the maximum supported resolution is 3840x2160. The requested size must also satisfy the model's current pixel and edge limits. The standard sizes 1024x1024, 1536x1024, and 1024x1536 are supported by the GPT image models; auto is supported for models that allow automatic sizing.

以下任何项:
string
enum
auto1024x10241536x10241024x1536256x256512x5121792x10241024x1792
moderation enum

Control the content-moderation level for images generated by the GPT image models. Must be either low for less restrictive filtering or auto (default value).

lowauto
background enum

Set the background of the generated image(s). This parameter is only supported for the GPT image models. Must be one of transparent, opaque, or auto (default value). When auto is used, the model will automatically determine the best background for the image. gpt-image-2.5-sunburst and gpt-image-2.5-flare, including their 2026-09-08 snapshots, support opaque and transparent backgrounds. Transparent backgrounds are available for supported GPT Image models. For gpt-image-2 and gpt-image-2-2026-04-21, this support is in preview. When using transparent, set the output format to png or webp.

transparentopaqueauto
style enum

Legacy style parameter for retired image models. Unsupported for GPT image models; describe the desired style in the prompt instead.

vividnatural
safety_identifier string | null

A stable identifier for an end user in your organization, used for safety monitoring and abuse detection. Hash a username or email address to avoid sending identifying information. A non-empty value takes precedence over the deprecated user parameter. If omitted, null, or empty, the API uses user when available. Learn more.

user string

Deprecated: use safety_identifier instead. This parameter remains accepted for backward compatibility and is used when safety_identifier is omitted, null, or empty. Learn more.

响应

The request has succeeded.

正文

Content-Type: application/json
safety_identifier string | null

The effective safety identifier used for safety monitoring and abuse detection. This is the non-empty safety_identifier from the request, or the deprecated user value when safety_identifier is omitted, null, or empty.

created integer 必需

The Unix timestamp (in seconds) of when the image was created.

data OpenAI.Image[]

The list of generated images.

background enum

The background parameter used for the image generation. Either transparent or opaque.

transparentopaque
output_format enum

The output format of the image generation. Either png, webp, or jpeg.

pngwebpjpeg
size string | enum

The image dimensions as a WIDTHxHEIGHT string, for example 1536x864.

以下任何项:
string
enum
1024x10241024x15361536x1024
quality enum

The quality of the image generated. One of low, medium, high, xhigh, or max.

lowmediumhighxhighmax
usage OpenAI.ImageGenUsage

For gpt-image-1 only, the token usage information for the image generation.

input_tokens integer 必需
total_tokens integer 必需
output_tokens integer 必需
output_tokens_details OpenAI.ImageGenOutputTokensDetails

The output token details for the image generation.

image_tokens integer 必需
text_tokens integer 必需
input_tokens_details OpenAI.ImageGenInputUsageDetails 必需

The input tokens detailed information for the image generation.

text_tokens integer 必需
image_tokens integer 必需

Client error

正文

Content-Type: application/json
error OpenAI.Error 必需
code string | null 必需
message string 必需
param string | null
type string
misalignment OpenAI.MisalignmentErrorDetailsResource
review_target string | null
error_type string | enum
以下任何项:
string
enum
potentially_unintended_data_transferpotentially_unintended_data_accesspotentially_unintended_destructive_activityother
detailed_explanation string

The public explanation for this block.

steer OpenAI._MisalignmentSteer
message string 必需

The public continuation instruction.

details OpenAI.Error[]
additionalInfo object
debugInfo object

Server error

正文

Content-Type: application/json
error OpenAI.Error 必需
code string | null 必需
message string 必需
param string | null
type string
misalignment OpenAI.MisalignmentErrorDetailsResource
review_target string | null
error_type string | enum
以下任何项:
string
enum
potentially_unintended_data_transferpotentially_unintended_data_accesspotentially_unintended_destructive_activityother
detailed_explanation string

The public explanation for this block.

steer OpenAI._MisalignmentSteer
message string 必需

The public continuation instruction.

details OpenAI.Error[]
additionalInfo object
debugInfo object

请求

curl https://api.openai.com/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-image-1.5",
    "prompt": "A cute baby sea otter",
    "n": 1,
    "size": "1024x1024"
  }'
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ.get("OPENAI_API_KEY"),  # This is the default and can be omitted
)
for image in client.images.generate(
    prompt="A cute baby sea otter",
):
  print(image)
import OpenAI from "openai";
import { writeFile } from "fs/promises";

const client = new OpenAI();

const img = await client.images.generate({
  model: "gpt-image-1.5",
  prompt: "A cute baby sea otter",
  n: 1,
  size: "1024x1024"
});

const imageBuffer = Buffer.from(img.data[0].b64_json, "base64");
await writeFile("output.png", imageBuffer);
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted
});

const imagesResponse = await client.images.generate({ prompt: 'A cute baby sea otter' });

console.log(imagesResponse);
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go"
    "github.com/openai/openai-go/option"
)

func main() {
    client := openai.NewClient(
        option.WithAPIKey("My API Key"),
    )
    imagesResponse, err := client.Images.Generate(context.TODO(), openai.ImageGenerateParams{
        Prompt: "A cute baby sea otter",
    })
    if err != nil {
        panic(err.Error())
    }
    fmt.Printf("%+v
", imagesResponse)
}
package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.images.ImageGenerateParams;
import com.openai.models.images.ImagesResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ImageGenerateParams params = ImageGenerateParams.builder()
            .prompt("A cute baby sea otter")
            .build();
        ImagesResponse imagesResponse = client.images().generate(params);
    }
}
require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

images_response = openai.images.generate(prompt: "A cute baby sea otter")

puts(images_response)

响应

{
  "created": 1713833628,
  "data": [
    {
      "b64_json": "..."
    }
  ],
  "usage": {
    "total_tokens": 100,
    "input_tokens": 50,
    "output_tokens": 50,
    "input_tokens_details": {
      "text_tokens": 10,
      "image_tokens": 40
    }
  }
}

请求

curl https://api.openai.com/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-image-1.5",
    "prompt": "A cute baby sea otter",
    "n": 1,
    "size": "1024x1024",
    "stream": true
  }' \
  --no-buffer
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ.get("OPENAI_API_KEY"),  # This is the default and can be omitted
)
for image in client.images.generate(
    prompt="A cute baby sea otter",
):
  print(image)
import OpenAI from "openai";

const client = new OpenAI();

const stream = await client.images.generate({
  model: "gpt-image-1.5",
  prompt: "A cute baby sea otter",
  n: 1,
  size: "1024x1024",
  stream: true,
});

for await (const event of stream) {
  console.log(event);
}
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted
});

const imagesResponse = await client.images.generate({ prompt: 'A cute baby sea otter' });

console.log(imagesResponse);
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go"
    "github.com/openai/openai-go/option"
)

func main() {
    client := openai.NewClient(
        option.WithAPIKey("My API Key"),
    )
    imagesResponse, err := client.Images.Generate(context.TODO(), openai.ImageGenerateParams{
        Prompt: "A cute baby sea otter",
    })
    if err != nil {
        panic(err.Error())
    }
    fmt.Printf("%+v
", imagesResponse)
}
package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.images.ImageGenerateParams;
import com.openai.models.images.ImagesResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ImageGenerateParams params = ImageGenerateParams.builder()
            .prompt("A cute baby sea otter")
            .build();
        ImagesResponse imagesResponse = client.images().generate(params);
    }
}
require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

images_response = openai.images.generate(prompt: "A cute baby sea otter")

puts(images_response)

响应

event: image_generation.partial_image
data: {"type":"image_generation.partial_image","b64_json":"...","partial_image_index":0}

event: image_generation.completed
data: {"type":"image_generation.completed","b64_json":"...","usage":{"total_tokens":100,"input_tokens":50,"output_tokens":50,"input_tokens_details":{"text_tokens":10,"image_tokens":40}}}
zh-cn
你的隐私选择
  • AI 免责声明
  • 早期版本
  • 博客
  • 参与
  • 隐私
  • 消费者健康隐私
  • 使用条款
  • 商标
  • © Microsoft 2026