> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aiandgpu.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Text to Image

export const OpenAIApiResponse = ({successJson, successTitle = "200 - Success", streaming = false}) => {
  const error400 = `{
    "error": {
        "code": "invalid_params",
        "message": "parameter 'ARGUMENT' is required",
        "param": null,
        "type": "invalid_request_error"
    }
}`;
  const error401 = `{
    "error": {
        "code": "auth_invalid",
        "message": "Invalid API Key",
        "param": null,
        "type": "authentication_error"
    }
}`;
  const error402 = `{
    "error": {
        "code": "insufficient_quota",
        "message": "You exceeded your current quota, please check your plan and billing details.",
        "param": null,
        "type": "insufficient_quota_error"
    }
}`;
  const error403 = `{
    "error": {
        "code": "permission_error",
        "message": "You have no permission to access the model.",
        "type": "permission_error",
        "param": null
    }
}`;
  const error404 = `{
    "error": {
        "code": "invalid_request_error",
        "message": "Invalid URL",
        "param": null,
        "type": "invalid_request_error"
    }
}`;
  const error429 = `{
    "error": {
        "code": "rate_limit_exceeded",
        "message": "Rate limit reached",
        "param": null,
        "type": "rate_limit_error"
    }
}`;
  const error500 = `{
    "error": {
        "code": "server_error",
        "message": "Internal server error",
        "param": null,
        "type": "server_error"
    }
}`;
  return <>
      <h2>Response Examples</h2>

      <CodeGroup>
        <CodeBlock language={streaming ? "text" : "json"} filename={streaming ? "200 - Streaming Response (SSE)" : successTitle}>
          {successJson}
        </CodeBlock>
        <CodeBlock language="json" filename="400 - Bad Request">
          {error400}
        </CodeBlock>
        <CodeBlock language="json" filename="401 - Unauthorized">
          {error401}
        </CodeBlock>
        <CodeBlock language="json" filename="402 - Insufficient Balance">
          {error402}
        </CodeBlock>
        <CodeBlock language="json" filename="403 - Permission Denied">
          {error403}
        </CodeBlock>
        <CodeBlock language="json" filename="404 - Invalid URL">
          {error404}
        </CodeBlock>
        <CodeBlock language="json" filename="429 - Too Many Requests">
          {error429}
        </CodeBlock>
        <CodeBlock language="json" filename="500 - Internal Server Error">
          {error500}
        </CodeBlock>
      </CodeGroup>
    </>;
};

## Authorization

* **Auth Type**: `Bearer Auth` (In: `header`)
* **Format**: `Authorization: Bearer <YOUR_API_KEY>`
* **Description**: Use `Bearer <YOUR_API_KEY>`. Format: `Authorization: Bearer sk-xxxxxx.`
* **API Key**: where <strong>API Key</strong> is your <a href="https://developer.aiandgpu.com" target="_blank" rel="noopener noreferrer">AGCloud API KEY</a>

Generate images from a text prompt using `gpt-image-2`. Send a JSON request to `https://aiandgpu.com/v1/images/generations`.

## Request Examples

<CodeGroup>
  ```bash cURL theme={null}
  curl --location 'https://aiandgpu.com/v1/images/generations' \
    --header 'Authorization: Bearer <YOUR_API_KEY>' \
    --header 'Content-Type: application/json' \
    --data '{
      "model": "gpt-image-2",
      "prompt": "Draw a watercolor illustration of a red panda reading under a maple tree.",
      "n": 1,
      "size": "1024x1024",
      "quality": "medium",
      "output_format": "png"
    }'
  ```

  ```python Python theme={null}
  import base64
  import requests

  response = requests.post(
      "https://aiandgpu.com/v1/images/generations",
      headers={"Authorization": "Bearer <YOUR_API_KEY>"},
      json={
          "model": "gpt-image-2",
          "prompt": "Draw a watercolor illustration of a red panda reading under a maple tree.",
          "n": 1,
          "size": "1024x1024",
          "quality": "medium",
          "output_format": "png",
      },
      timeout=600,
  )
  response.raise_for_status()
  data = response.json()
  with open("generated.png", "wb") as image_file:
      image_file.write(base64.b64decode(data["data"][0]["b64_json"]))
  ```

  ```javascript JavaScript theme={null}
  // Node.js 18+; save as an .mjs file.
  import { writeFile } from "node:fs/promises";

  const response = await fetch("https://aiandgpu.com/v1/images/generations", {
    method: "POST",
    headers: {
      Authorization: "Bearer <YOUR_API_KEY>",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "gpt-image-2",
      prompt: "Draw a watercolor illustration of a red panda reading under a maple tree.",
      n: 1,
      size: "1024x1024",
      quality: "medium",
      output_format: "png",
    }),
  });
  if (!response.ok) throw new Error(await response.text());
  const data = await response.json();
  await writeFile("generated.png", Buffer.from(data.data[0].b64_json, "base64"));
  ```

  ```go Go theme={null}
  package main

  import (
      "bytes"
      "encoding/json"
      "fmt"
      "io"
      "net/http"
      "time"
  )

  func main() {
      body, err := json.Marshal(map[string]any{
          "model": "gpt-image-2",
          "prompt": "Draw a watercolor illustration of a red panda reading under a maple tree.",
          "n": 1,
          "size": "1024x1024",
          "quality": "medium",
          "output_format": "png",
      })
      if err != nil { panic(err) }
      req, err := http.NewRequest("POST", "https://aiandgpu.com/v1/images/generations", bytes.NewReader(body))
      if err != nil { panic(err) }
      req.Header.Set("Authorization", "Bearer <YOUR_API_KEY>")
      req.Header.Set("Content-Type", "application/json")
      client := &http.Client{Timeout: 10 * time.Minute}
      res, err := client.Do(req)
      if err != nil { panic(err) }
      defer res.Body.Close()
      result, err := io.ReadAll(res.Body)
      if err != nil { panic(err) }
      if res.StatusCode >= 400 { panic(string(result)) }
      fmt.Println(string(result))
  }
  ```

  ```java Java theme={null}
  // Java 11+; save as GenerateImage.java.
  import java.net.URI;
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;
  import java.time.Duration;

  public class GenerateImage {
      public static void main(String[] args) throws Exception {
          String body = "{\"model\":\"gpt-image-2\","
              + "\"prompt\":\"Draw a watercolor illustration of a red panda reading under a maple tree.\","
              + "\"n\":1,\"size\":\"1024x1024\",\"quality\":\"medium\",\"output_format\":\"png\"}";
          HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create("https://aiandgpu.com/v1/images/generations"))
              .timeout(Duration.ofMinutes(10))
              .header("Authorization", "Bearer <YOUR_API_KEY>")
              .header("Content-Type", "application/json")
              .POST(HttpRequest.BodyPublishers.ofString(body))
              .build();
          HttpResponse<String> response = HttpClient.newHttpClient()
              .send(request, HttpResponse.BodyHandlers.ofString());
          if (response.statusCode() >= 400) throw new RuntimeException(response.body());
          System.out.println(response.body());
      }
  }
  ```

  ```php PHP theme={null}
  <?php

  $curl = curl_init("https://aiandgpu.com/v1/images/generations");
  curl_setopt_array($curl, [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POST => true,
      CURLOPT_TIMEOUT => 600,
      CURLOPT_HTTPHEADER => [
          "Authorization: Bearer <YOUR_API_KEY>",
          "Content-Type: application/json",
      ],
      CURLOPT_POSTFIELDS => json_encode([
          "model" => "gpt-image-2",
          "prompt" => "Draw a watercolor illustration of a red panda reading under a maple tree.",
          "n" => 1,
          "size" => "1024x1024",
          "quality" => "medium",
          "output_format" => "png",
      ]),
  ]);
  $response = curl_exec($curl);
  if ($response === false) throw new RuntimeException(curl_error($curl));
  $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  curl_close($curl);
  if ($status >= 400) throw new RuntimeException($response);
  echo $response;
  ```

  ```csharp C# theme={null}
  // .NET 6+
  using System;
  using System.Net.Http;
  using System.Net.Http.Json;

  using var client = new HttpClient { Timeout = TimeSpan.FromMinutes(10) };
  client.DefaultRequestHeaders.Add("Authorization", "Bearer <YOUR_API_KEY>");
  using var response = await client.PostAsJsonAsync(
      "https://aiandgpu.com/v1/images/generations",
      new {
          model = "gpt-image-2",
          prompt = "Draw a watercolor illustration of a red panda reading under a maple tree.",
          n = 1,
          size = "1024x1024",
          quality = "medium",
          output_format = "png"
      }
  );
  response.EnsureSuccessStatusCode();
  Console.WriteLine(await response.Content.ReadAsStringAsync());
  ```
</CodeGroup>

<OpenAIApiResponse
  successJson={`{
    "created": 1777262313,
    "data": [
        {
            "b64_json": "<BASE64_ENCODED_IMAGE>"
        }
    ],
    "background": "opaque",
    "output_format": "png",
    "quality": "medium",
    "size": "1024x1024",
    "usage": {
      "total_tokens": 100,
      "input_tokens": 50,
      "output_tokens": 50,
      "input_tokens_details": {
        "text_tokens": 10,
        "image_tokens": 40
      }
    }
}`}
/>

The success response is illustrative; replace the Base64 placeholder with actual image data before decoding. OpenAI GPT Image responses use `data[].b64_json`, not image URLs. Do not send `response_format` or `style`; describe the desired style in `prompt`.

## Request Parameters

| Field | Type | Required | Default | Description |
| :- | :- | :- | :- | :- |
| `model` | string | ✅ | - | Use `gpt-image-2`. |
| `prompt` | string | ✅ | - | Image description; maximum 32,000 characters. |
| `n` | integer | - | 1 | Image count, 1–10. |
| `size` | string | - | `auto` | `auto` or `WIDTHxHEIGHT`; see constraints below. |
| `quality` | string | - | `auto` | `auto`, `low`, `medium`, or `high`. |
| `background` | string | - | `auto` | `auto`, `opaque`, or `transparent` (preview for GPT Image 2). Transparency requires PNG or WebP. |
| `moderation` | string | - | `auto` | `auto` or `low` (less restrictive filtering). |
| `output_format` | string | - | `png` | `png`, `jpeg`, or `webp`. |
| `output_compression` | integer | - | 100 | 0–100; JPEG/WebP only. |
| `stream` | boolean | - | `false` | Enable server-sent events (SSE). |
| `partial_images` | integer | - | - | 0–3 previews when streaming; 0 returns only the final image. |
| `safety_identifier` | string | - | - | Hashed end-user identifier; maximum 128 characters. |
| `user` | string | - | - | Deprecated fallback for `safety_identifier`. |

These fields follow the [OpenAI Create image reference](https://developers.openai.com/api/reference/resources/images/methods/generate).

### Size and streaming notes

For `gpt-image-2`, both dimensions must be multiples of 16, each at most 3840 pixels. The longer edge must not exceed three times the shorter edge, and total pixels must be between 655,360 and 8,294,400. Examples include `1024x1024`, `1536x1024`, `1024x1536`, and `1536x864`. Resolutions above `2560x1440` are experimental.

With `stream: true`, consume SSE events instead of parsing a single JSON response. Partial images use `image_generation.partial_image`; the final image uses `image_generation.completed`. Image bytes are Base64-encoded in `b64_json`. Fewer previews than requested may arrive if generation completes early; each preview adds 100 image output tokens.

See the [OpenAI image generation guide](https://developers.openai.com/api/docs/guides/image-generation) for sizing and streaming details.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.