> ## 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.

# Génération d'images GPT-Image-2 (canal officiel)

>  - Modèle officiel OpenAI `gpt-image-2`, basé sur le protocole compatible `/v1/images/generations`
- Traitement asynchrone, renvoie un `task_id` pour les requêtes ultérieures
- Texte-vers-image / image-vers-image / inpainting (mask) — tout-en-un
- Nouveau champ de niveau `resolution` — sélection 1K / 2K / 4K
- 15 ratios d'aspect pris en charge sur les niveaux 1K / 2K / 4K
- Jusqu'à 4 images par requête, jusqu'à 16 images de référence
- Alignement de paramètres à 95 % avec `gpt-image-1.5-official` — la migration ne nécessite qu'un changement de nom de modèle 

<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>

## Autorisations

<ParamField header="Authorization" type="string" required>
  Tous les points de terminaison nécessitent une authentification Bearer Token

  Obtenir votre clé API :

  Rendez-vous sur la [page de gestion des clés API](https://apimart.ai/keys) pour obtenir votre clé API

  Incluez-la dans l'en-tête de la requête :

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

## Body

<ParamField body="model" type="string" default="gpt-image-2-official" required>
  Nom du modèle de génération d'images

  Fixé à `gpt-image-2-official` (modèle officiel OpenAI gpt-image-2)
</ParamField>

<ParamField body="prompt" type="string" required>
  Description textuelle pour la génération d'images

  * Prend en charge l'anglais et le chinois, des descriptions détaillées sont recommandées
  * Modération de contenu / examen de sécurité avant soumission — les violations sont rejetées immédiatement
</ParamField>

<ParamField body="size" type="string" default="1:1">
  Ratio d'aspect de l'image

  À l'extérieur, des valeurs de ratio sont utilisées ; en interne, elles sont automatiquement associées aux pixels réels selon `resolution`.

  Ratios pris en charge, plus `auto` pour laisser le serveur choisir automatiquement un ratio adapté :

  * `auto` — Automatique (le serveur choisit un ratio selon le prompt / les images de référence)
  * `1:1` — Carré (par défaut, avatars sociaux / logos)
  * `3:2` — Paysage (ratio courant de reflex numérique)
  * `2:3` — Portrait (affiches verticales)
  * `4:3` — Paysage (moniteur classique / diaporama)
  * `3:4` — Portrait
  * `5:4` — Paysage
  * `4:5` — Portrait (publication Instagram verticale)
  * `16:9` — Paysage (miniature vidéo grand écran)
  * `9:16` — Portrait (plein écran téléphone / couverture de vidéo courte)
  * `2:1` — Paysage (bannière Web)
  * `1:2` — Portrait
  * `3:1` — Paysage (bannière ultra-large)
  * `1:3` — Portrait (affiche extra-haute)
  * `21:9` — Paysage (ultra-large cinématographique)
  * `9:21` — Portrait

  Les dimensions en pixels peuvent également être transmises directement, par exemple `1881x836` / `887x1774`.

  <Warning>
    Lorsque `size` est défini sur `auto`, le ratio par défaut est `1:1`.
  </Warning>
</ParamField>

<ParamField body="resolution" type="string" default="1k">
  Niveau de résolution (**nouveau champ**)

  Contrôle la netteté réelle de la sortie.

  * `1k` — Base 1024, économique pour une utilisation quotidienne (par défaut)
  * `2k` — Base 2048, adapté aux affiches / besoins en haute définition
  * `4k` — Base 3840, prend en charge les 15 ratios du tableau de correspondance ci-dessous

  <Warning>
    La 4K prend en charge les 15 ratios du tableau de correspondance ci-dessous ; vous pouvez également transmettre les dimensions en pixels du tableau directement via `size`.
  </Warning>
</ParamField>

<ParamField body="quality" type="string" default="auto">
  Qualité de l'image

  * `auto` — Automatique (par défaut, généralement équivalent à `low`)
  * `low` — Rapide et économique, suffisant pour des contours grossiers
  * `medium` — Équilibré
  * `high` — Précision maximale (4K + high peut prendre plus de 120 s)
</ParamField>

<ParamField body="background" type="string" default="auto">
  Mode d'arrière-plan

  * `auto` — Automatique (par défaut)
  * `opaque` — Opaque
  * `transparent` — ⚠️ **gpt-image-2-official ne prend pas en charge les arrière-plans transparents ; le système rétrograde silencieusement vers `auto`**
</ParamField>

<ParamField body="moderation" type="string" default="auto">
  Force de modération

  * `auto` — Force de modération par défaut
  * `low` — Modération plus permissive
</ParamField>

<ParamField body="output_format" type="string" default="png">
  Format de sortie

  * `png` — Par défaut
  * `jpeg` — Fichiers plus petits
  * `webp` — Optimal pour les navigateurs modernes
</ParamField>

<ParamField body="output_compression" type="integer">
  Niveau de compression de sortie, plage `0-100`

  * N'est effectif que pour `jpeg` / `webp`
</ParamField>

<ParamField body="n" type="integer" default="1">
  Nombre d'images à générer

  Plage : `1 ~ 4`

  <Warning>
    Doit être un nombre brut (par exemple `1`), ne pas mettre entre guillemets
  </Warning>
</ParamField>

<ParamField body="image_urls" type="array">
  Tableau d'URL d'images de référence

  <Expandable title="Détails">
    * 20 Mo maximum par image, plafond total de 256 Mo
    * Jusqu'à **16** images de référence ; au-delà, sera rejeté
    * Doivent être des URL d'images publiquement accessibles et stables
  </Expandable>
</ParamField>

<ParamField body="mask_url" type="string">
  URL de l'image de masque, utilisée pour l'inpainting

  * Doit être utilisé conjointement avec `image_urls`

  <Warning>
    1. Assurez-vous que l'image de masque possède un canal Alpha avant de la téléverser.

    2. Les dimensions de l'image de masque doivent **correspondre à la première image de référence**.
  </Warning>
</ParamField>

## Correspondance Size × Resolution

`size × resolution` → pixels réels OpenAI (15 ratios × 3 niveaux) :

| 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** |

> Note : Certaines dimensions sont approximées à des multiples de 16 et à des limites de pixels, comme `3:2` / `2:3` @ 2K qui est 2048×1360 et `21:9` @ 4K qui est 3840×1648. Référez-vous aux pixels réels du tableau comme source de vérité.

## Exemples d'utilisation

**Texte-vers-image (requête minimale)**

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

**Affiche haute définition 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
}
```

**Fond d'écran 4K**

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

**Image-vers-image (fusion multi-références)**

```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 (masque)**

```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"
}
```

**Plusieurs images (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
}
```

**Chaîne de pixels directe (avancée)**

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

## Response

<ResponseField name="code" type="integer">
  Code de statut de la réponse
</ResponseField>

<ResponseField name="data" type="array">
  Tableau de données de réponse

  <Expandable title="Propriétés">
    <ResponseField name="status" type="string">
      Statut de la tâche

      * `submitted` — Soumise
    </ResponseField>

    <ResponseField name="task_id" type="string">
      Identifiant unique de la tâche, utilisé pour les requêtes ultérieures de résultats
    </ResponseField>
  </Expandable>
</ResponseField>

## Interrogation des résultats de tâche

Après une soumission réussie, un `task_id` est renvoyé. Interrogez l'état de la tâche via `GET /v1/tasks/{task_id}`, voir [API d'interrogation des tâches](/fr/api-reference/tasks/status) pour plus de détails.

### Exemple de réponse en cas de succès

```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
        }
      ]
    }
  }
}
```

Flux de statuts de la tâche : `submitted` → `in_progress` → `completed` / `failed`.

Accès à l'image : `data.result.images[0].url[0]`.
