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

# Generación de imágenes con GPT-Image-2 canal oficial

>  - Modelo oficial `gpt-image-2` de OpenAI, basado en el protocolo compatible `/v1/images/generations`
- Procesamiento asíncrono, devuelve `task_id` para consultas posteriores
- Texto a imagen / imagen a imagen / inpainting (máscara) — todo en uno
- Nuevo campo de nivel `resolution` — selección de 1K / 2K / 4K
- 15 proporciones admitidas en los niveles 1K / 2K / 4K
- Hasta 4 imágenes por solicitud, hasta 16 imágenes de referencia
- 95% de alineación de parámetros con `gpt-image-1.5-official` — la migración solo requiere cambiar el nombre del modelo 

<RequestExample>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.apimart.ai/v1/images/generations \
    --header 'Authorization: Bearer <token>' \
    --header 'Content-Type: application/json' \
    --data '{
      "model": "gpt-image-2-official",
      "prompt": "An ancient castle beneath a starry sky",
      "size": "16:9",
      "resolution": "2k",
      "quality": "high",
      "n": 1
    }'
  ```

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

  url = "https://api.apimart.ai/v1/images/generations"

  payload = {
      "model": "gpt-image-2-official",
      "prompt": "An ancient castle beneath a starry sky",
      "size": "16:9",
      "resolution": "2k",
      "quality": "high",
      "n": 1
  }

  headers = {
      "Authorization": "Bearer <token>",
      "Content-Type": "application/json"
  }

  response = requests.post(url, json=payload, headers=headers)

  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const url = "https://api.apimart.ai/v1/images/generations";

  const payload = {
    model: "gpt-image-2-official",
    prompt: "An ancient castle beneath a starry sky",
    size: "16:9",
    resolution: "2k",
    quality: "high",
    n: 1,
  };

  const headers = {
    Authorization: "Bearer <token>",
    "Content-Type": "application/json",
  };

  fetch(url, {
    method: "POST",
    headers: headers,
    body: JSON.stringify(payload),
  })
    .then((response) => response.json())
    .then((data) => console.log(data))
    .catch((error) => console.error("Error:", error));
  ```

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

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

  func main() {
      url := "https://api.apimart.ai/v1/images/generations"

      payload := map[string]interface{}{
          "model":      "gpt-image-2-official",
          "prompt":     "An ancient castle beneath a starry sky",
          "size":       "16:9",
          "resolution": "2k",
          "quality":    "high",
          "n":          1,
      }

      jsonData, _ := json.Marshal(payload)

      req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
      req.Header.Set("Authorization", "Bearer <token>")
      req.Header.Set("Content-Type", "application/json")

      client := &http.Client{}
      resp, err := client.Do(req)
      if err != nil {
          panic(err)
      }
      defer resp.Body.Close()

      body, _ := ioutil.ReadAll(resp.Body)
      fmt.Println(string(body))
  }
  ```

  ```java Java theme={null}
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;
  import java.net.URI;

  public class Main {
      public static void main(String[] args) throws Exception {
          String url = "https://api.apimart.ai/v1/images/generations";

          String payload = """
          {
            "model": "gpt-image-2-official",
            "prompt": "An ancient castle beneath a starry sky",
            "size": "16:9",
            "resolution": "2k",
            "quality": "high",
            "n": 1
          }
          """;

          HttpClient client = HttpClient.newHttpClient();
          HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create(url))
              .header("Authorization", "Bearer <token>")
              .header("Content-Type", "application/json")
              .POST(HttpRequest.BodyPublishers.ofString(payload))
              .build();

          HttpResponse<String> response = client.send(request,
              HttpResponse.BodyHandlers.ofString());

          System.out.println(response.body());
      }
  }
  ```

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

  $url = "https://api.apimart.ai/v1/images/generations";

  $payload = [
      "model" => "gpt-image-2-official",
      "prompt" => "An ancient castle beneath a starry sky",
      "size" => "16:9",
      "resolution" => "2k",
      "quality" => "high",
      "n" => 1
  ];

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      "Authorization: Bearer <token>",
      "Content-Type: application/json"
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  echo $response;
  ?>
  ```

  ```ruby Ruby theme={null}
  require 'net/http'
  require 'json'
  require 'uri'

  url = URI("https://api.apimart.ai/v1/images/generations")

  payload = {
    model: "gpt-image-2-official",
    prompt: "An ancient castle beneath a starry sky",
    size: "16:9",
    resolution: "2k",
    quality: "high",
    n: 1
  }

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(url)
  request["Authorization"] = "Bearer <token>"
  request["Content-Type"] = "application/json"
  request.body = payload.to_json

  response = http.request(request)
  puts response.body
  ```

  ```swift Swift theme={null}
  import Foundation

  let url = URL(string: "https://api.apimart.ai/v1/images/generations")!

  let payload: [String: Any] = [
      "model": "gpt-image-2-official",
      "prompt": "An ancient castle beneath a starry sky",
      "size": "16:9",
      "resolution": "2k",
      "quality": "high",
      "n": 1
  ]

  var request = URLRequest(url: url)
  request.httpMethod = "POST"
  request.setValue("Bearer <token>", forHTTPHeaderField: "Authorization")
  request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  request.httpBody = try? JSONSerialization.data(withJSONObject: payload)

  let task = URLSession.shared.dataTask(with: request) { data, response, error in
      if let error = error {
          print("Error: \(error)")
          return
      }

      if let data = data, let responseString = String(data: data, encoding: .utf8) {
          print(responseString)
      }
  }

  task.resume()
  ```

  ```csharp C# theme={null}
  using System;
  using System.Net.Http;
  using System.Text;
  using System.Threading.Tasks;

  class Program
  {
      static async Task Main(string[] args)
      {
          var url = "https://api.apimart.ai/v1/images/generations";

          var payload = @"{
              ""model"": ""gpt-image-2-official"",
              ""prompt"": ""An ancient castle beneath a starry sky"",
              ""size"": ""16:9"",
              ""resolution"": ""2k"",
              ""quality"": ""high"",
              ""n"": 1
          }";

          using var client = new HttpClient();
          client.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");

          var content = new StringContent(payload, Encoding.UTF8, "application/json");
          var response = await client.PostAsync(url, content);
          var result = await response.Content.ReadAsStringAsync();

          Console.WriteLine(result);
      }
  }
  ```

  ```dart Dart theme={null}
  import 'dart:convert';
  import 'package:http/http.dart' as http;

  void main() async {
    final url = Uri.parse('https://api.apimart.ai/v1/images/generations');

    final payload = {
      'model': 'gpt-image-2-official',
      'prompt': 'An ancient castle beneath a starry sky',
      'size': '16:9',
      'resolution': '2k',
      'quality': 'high',
      'n': 1,
    };

    final response = await http.post(
      url,
      headers: {
        'Authorization': 'Bearer <token>',
        'Content-Type': 'application/json',
      },
      body: jsonEncode(payload),
    );

    print(response.body);
  }
  ```

  ```r R theme={null}
  library(httr)
  library(jsonlite)

  url <- "https://api.apimart.ai/v1/images/generations"

  payload <- list(
    model = "gpt-image-2-official",
    prompt = "An ancient castle beneath a starry sky",
    size = "16:9",
    resolution = "2k",
    quality = "high",
    n = 1
  )

  response <- POST(
    url,
    add_headers(
      Authorization = "Bearer <token>",
      `Content-Type` = "application/json"
    ),
    body = toJSON(payload, auto_unbox = TRUE),
    encode = "raw"
  )

  cat(content(response, "text"))
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "code": 200,
    "data": [
      {
        "status": "submitted",
        "task_id": "task_01KPTXXXXXXXXXXXXXXX"
      }
    ]
  }
  ```

  ```json 400 theme={null}
  {
    "error": {
      "code": 400,
      "message": "Invalid parameters: size not allowed / resolution not supported / pixel violation, etc.",
      "type": "invalid_request_error"
    }
  }
  ```

  ```json 401 theme={null}
  {
    "error": {
      "code": 401,
      "message": "Authentication failed, please check your API key",
      "type": "authentication_error"
    }
  }
  ```

  ```json 402 theme={null}
  {
    "error": {
      "code": 402,
      "message": "Insufficient account balance, please top up and try again",
      "type": "payment_required"
    }
  }
  ```

  ```json 403 theme={null}
  {
    "error": {
      "code": 403,
      "message": "Access forbidden, you do not have permission to access this resource",
      "type": "permission_error"
    }
  }
  ```

  ```json 429 theme={null}
  {
    "error": {
      "code": 429,
      "message": "Too many requests, please try again later",
      "type": "rate_limit_error"
    }
  }
  ```

  ```json 500 theme={null}
  {
    "error": {
      "code": 500,
      "message": "Internal server error, please try again later",
      "type": "server_error"
    }
  }
  ```

  ```json 502 theme={null}
  {
    "error": {
      "code": 502,
      "message": "Bad gateway, the server is temporarily unavailable",
      "type": "bad_gateway"
    }
  }
  ```
</ResponseExample>

## Autorizaciones

<ParamField header="Authorization" type="string" required>
  Todos los endpoints requieren autenticación con Bearer Token

  Obtenga su API Key:

  Visite la [página de gestión de API Keys](https://apimart.ai/keys) para obtener su API Key

  Inclúyala en el encabezado de la solicitud:

  ```
  Authorization: Bearer YOUR_API_KEY
  ```
</ParamField>

## Body

<ParamField body="model" type="string" default="gpt-image-2-official" required>
  Nombre del modelo de generación de imágenes

  Fijo en `gpt-image-2-official` (modelo oficial gpt-image-2 de OpenAI)
</ParamField>

<ParamField body="prompt" type="string" required>
  Descripción textual para la generación de la imagen

  * Admite inglés y chino, se recomiendan descripciones detalladas
  * Moderación de contenido / revisión de seguridad antes del envío — las violaciones se rechazan inmediatamente
</ParamField>

<ParamField body="size" type="string" default="1:1">
  Proporción de la imagen

  Externamente usa valores de proporción; internamente se mapean a píxeles reales según `resolution`.

  Proporciones admitidas, más `auto` para dejar que el servidor elija una proporción adecuada automáticamente:

  * `auto` - Automática (el servidor elige una proporción según el prompt / imágenes de referencia)
  * `1:1` - Cuadrada (predeterminada, avatares sociales / logos)
  * `3:2` - Horizontal (proporción común de DSLR)
  * `2:3` - Vertical (pósters verticales)
  * `4:3` - Horizontal (monitor clásico / presentación de diapositivas)
  * `3:4` - Vertical
  * `5:4` - Horizontal
  * `4:5` - Vertical (publicación vertical de Instagram)
  * `16:9` - Horizontal (miniatura de video panorámico)
  * `9:16` - Vertical (pantalla completa de móvil / portada de video corto)
  * `2:1` - Horizontal (banner web)
  * `1:2` - Vertical
  * `3:1` - Horizontal (banner ultra panorámico)
  * `1:3` - Vertical (póster extra alto)
  * `21:9` - Horizontal (cinematográfico ultra panorámico)
  * `9:21` - Vertical

  También pueden pasarse dimensiones en píxeles directamente, como `1881x836` / `887x1774`.

  <Warning>
    Cuando `size` se establece en `auto`, la proporción predeterminada es `1:1`.
  </Warning>
</ParamField>

<ParamField body="resolution" type="string" default="1k">
  Nivel de resolución (**nuevo campo**)

  Controla la nitidez real de la salida.

  * `1k` - Línea base 1024, rentable para uso diario (predeterminado)
  * `2k` - Línea base 2048, adecuado para pósters / necesidades de alta definición
  * `4k` - Línea base 3840, admite las 15 proporciones de la tabla de mapeo siguiente

  <Warning>
    El 4K admite las 15 proporciones en la tabla de mapeo siguiente; también puede pasar las dimensiones en píxeles de la tabla directamente mediante `size`.
  </Warning>
</ParamField>

<ParamField body="quality" type="string" default="auto">
  Calidad de la imagen

  * `auto` - Automática (predeterminado, normalmente equivale a `low`)
  * `low` - Rápida y económica, suficiente para bocetos
  * `medium` - Equilibrada
  * `high` - Precisión máxima (4K + high puede tardar >120s)
</ParamField>

<ParamField body="background" type="string" default="auto">
  Modo de fondo

  * `auto` - Automático (predeterminado)
  * `opaque` - Opaco
  * `transparent` - ⚠️ **gpt-image-2-official no admite fondos transparentes; el sistema lo degrada silenciosamente a `auto`**
</ParamField>

<ParamField body="moderation" type="string" default="auto">
  Nivel de moderación

  * `auto` - Nivel de moderación predeterminado
  * `low` - Moderación más permisiva
</ParamField>

<ParamField body="output_format" type="string" default="png">
  Formato de salida

  * `png` - Predeterminado
  * `jpeg` - Archivos más pequeños
  * `webp` - Óptimo para navegadores modernos
</ParamField>

<ParamField body="output_compression" type="integer">
  Nivel de compresión de salida, rango `0-100`

  * Solo efectivo para `jpeg` / `webp`
</ParamField>

<ParamField body="n" type="integer" default="1">
  Número de imágenes a generar

  Rango: `1 ~ 4`

  <Warning>
    Debe ser un número puro (p. ej., `1`), no lo envuelva en comillas
  </Warning>
</ParamField>

<ParamField body="image_urls" type="array">
  Array de URLs de imágenes de referencia

  <Expandable title="Detalles">
    * Máximo 20 MB por imagen, límite total de 256 MB
    * Hasta **16** imágenes de referencia; las que excedan serán rechazadas
    * Deben ser URLs de imagen estables y accesibles públicamente
  </Expandable>
</ParamField>

<ParamField body="mask_url" type="string">
  URL de la imagen de máscara, usada para inpainting

  * Debe usarse junto con `image_urls`

  <Warning>
    1. Asegúrese de que la imagen de máscara tenga un canal Alpha antes de cargarla.

    2. Las dimensiones de la imagen de máscara deben **coincidir con la primera imagen de referencia**.
  </Warning>
</ParamField>

## Mapeo Size × Resolution

`size × resolution` → píxeles reales de OpenAI (15 proporciones × 3 niveles):

| size   | `1k`                | `2k`      | `4k`          |
| ------ | ------------------- | --------- | ------------- |
| `1:1`  | 1024×1024           | 2048×2048 | **2880×2880** |
| `3:2`  | 1536×1024           | 2048×1360 | **3520×2336** |
| `2:3`  | 1024×1536           | 1360×2048 | **2336×3520** |
| `4:3`  | 1024×768            | 2048×1536 | **3312×2480** |
| `3:4`  | 768×1024            | 1536×2048 | **2480×3312** |
| `5:4`  | 1280×1024           | 2560×2048 | **3216×2576** |
| `4:5`  | 1024×1280           | 2048×2560 | **2576×3216** |
| `16:9` | 1536×864            | 2048×1152 | **3840×2160** |
| `9:16` | 864×1536            | 1152×2048 | **2160×3840** |
| `2:1`  | 2048×1024           | 2688×1344 | **3840×1920** |
| `1:2`  | 1024×2048           | 1344×2688 | **1920×3840** |
| `3:1`  | 1881×836 / 1536×512 | 3072×1024 | **3840×1280** |
| `1:3`  | 887×1774 / 512×1536 | 1024×3072 | **1280×3840** |
| `21:9` | 2016×864            | 2688×1152 | **3840×1648** |
| `9:21` | 864×2016            | 1152×2688 | **1648×3840** |

> Nota: Algunas dimensiones se aproximan en función de múltiplos de 16 y límites de píxeles, como `3:2` / `2:3` @ 2K siendo 2048×1360 y `21:9` @ 4K siendo 3840×1648. Use los píxeles reales de la tabla como fuente de verdad.

## Ejemplos de uso

**Texto a imagen (solicitud mínima)**

```json theme={null}
{
  "model": "gpt-image-2-official",
  "prompt": "An ancient castle beneath a starry sky"
}
```

**Póster en alta definición 2K**

```json theme={null}
{
  "model": "gpt-image-2-official",
  "prompt": "Cyberpunk night scene",
  "size": "16:9",
  "resolution": "2k",
  "quality": "high",
  "output_format": "jpeg",
  "output_compression": 90
}
```

**Fondo de pantalla 4K**

```json theme={null}
{
  "model": "gpt-image-2-official",
  "prompt": "Snow mountain sunrise panorama",
  "size": "16:9",
  "resolution": "4k",
  "quality": "high",
  "n": 1
}
```

**Imagen a imagen (fusión multireferencia)**

```json theme={null}
{
  "model": "gpt-image-2-official",
  "prompt": "Fuse the two reference images into a single illustration poster, preserving the main silhouettes",
  "size": "1:1",
  "quality": "high",
  "image_urls": [
    "https://your-cdn.com/input-a.png",
    "https://your-cdn.com/input-b.png"
  ]
}
```

**Inpainting (máscara)**

```json theme={null}
{
  "model": "gpt-image-2-official",
  "prompt": "Replace the background with a desert sunset",
  "size": "1:1",
  "quality": "medium",
  "image_urls": ["https://your-cdn.com/photo.png"],
  "mask_url": "https://your-cdn.com/mask.png"
}
```

**Múltiples imágenes (n > 1)**

```json theme={null}
{
  "model": "gpt-image-2-official",
  "prompt": "Four minimalist poster variations of a red fox",
  "size": "1:1",
  "quality": "low",
  "n": 4
}
```

**Cadena de píxeles directa (avanzado)**

```json theme={null}
{
  "model": "gpt-image-2-official",
  "prompt": "wide cinematic shot",
  "size": "3840x2160",
  "quality": "high"
}
```

## Response

<ResponseField name="code" type="integer">
  Código de estado de la respuesta
</ResponseField>

<ResponseField name="data" type="array">
  Array de datos de la respuesta

  <Expandable title="Propiedades">
    <ResponseField name="status" type="string">
      Estado de la tarea

      * `submitted` - Enviada
    </ResponseField>

    <ResponseField name="task_id" type="string">
      Identificador único de la tarea, usado para consultas posteriores de resultados
    </ResponseField>
  </Expandable>
</ResponseField>

## Consulta de resultados de la tarea

Tras un envío correcto, se devuelve un `task_id`. Consulte el estado de la tarea mediante `GET /v1/tasks/{task_id}`, consulte la [API de consulta de tareas](/es/api-reference/tasks/status) para más detalles.

### Ejemplo de respuesta exitosa

```json theme={null}
{
  "code": 200,
  "data": {
    "id": "task_01KPTXXXXXXXXXXXXXXX",
    "status": "completed",
    "progress": 100,
    "actual_time": 46,
    "cost": 0.05279,
    "credits_cost": 0.5279,
    "result": {
      "images": [
        {
          "url": [
            "https://upload.apimart.ai/f/image/xxxxxxxx-gpt_image_2_official_task_xxx_0.png"
          ],
          "expires_at": 1776928569
        }
      ]
    }
  }
}
```

Flujo de estado de la tarea: `submitted` → `in_progress` → `completed` / `failed`.

Acceso a la imagen: `data.result.images[0].url[0]`.
