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

# De imagen a imagen (edición de imágenes)

> Genera o edita imágenes a partir de imágenes de referencia con GPT Image 2 mediante la API de BetterToken compatible con OpenAI.

`POST /v1/images/edits`

El endpoint de imagen a imagen usa un cuerpo de solicitud `multipart/form-data`. Sube una o varias imágenes de referencia y envía el prompt y los parámetros como campos de formulario.

<Note>
  Usa `https://www.bettertoken.ai/v1` como `Base URL`. Envía tu BetterToken API Key mediante `Authorization: Bearer YOUR_API_KEY`.
</Note>

<Tip>
  Puedes completar los campos del formulario y subir imágenes de referencia en el Playground de la derecha. Después, envía la solicitud directamente a `https://www.bettertoken.ai/v1/images/edits`.
</Tip>

<Warning>
  No uses un cuerpo JSON normal para las solicitudes de imagen a imagen. Envía los campos de texto y archivo mediante `multipart/form-data`.
</Warning>

## Valores recomendados

Envía estos campos de forma explícita en cada solicitud:

```text theme={null}
model=gpt-image-2
n=1
response_format=b64_json
output_format=png
```

Usa `image` para una sola imagen de referencia. Para varias imágenes de referencia, repite el campo `image[]`.

## Una imagen de referencia

```bash theme={null}
curl 'https://www.bettertoken.ai/v1/images/edits' \
  -H 'Authorization: Bearer sk-***REDACTED***' \
  -F 'model=gpt-image-2' \
  -F 'prompt=Use this reference image to create a more polished square product hero image while keeping the main style consistent.' \
  -F 'n=1' \
  -F 'size=1024x1024' \
  -F 'response_format=b64_json' \
  -F 'output_format=png' \
  -F 'image=@reference.png'
```

## Varias imágenes de referencia

```bash theme={null}
curl 'https://www.bettertoken.ai/v1/images/edits' \
  -H 'Authorization: Bearer sk-***REDACTED***' \
  -F 'model=gpt-image-2' \
  -F 'prompt=Combine these reference images into one consistent promotional poster.' \
  -F 'n=1' \
  -F 'size=1024x1024' \
  -F 'response_format=b64_json' \
  -F 'output_format=png' \
  -F 'image[]=@reference-1.png' \
  -F 'image[]=@reference-2.jpg' \
  -F 'image[]=@reference-3.png'
```

## Ejemplo con Python

```python theme={null}
import requests

url = "https://www.bettertoken.ai/v1/images/edits"
headers = {
    "Authorization": "Bearer sk-***REDACTED***",
}

data = {
    "model": "gpt-image-2",
    "prompt": "Use this reference image to create a more polished square product hero image while keeping the main style consistent.",
    "n": "1",
    "size": "1024x1024",
    "response_format": "b64_json",
    "output_format": "png",
}

with open("reference.png", "rb") as image_file:
    files = {
        "image": ("reference.png", image_file, "image/png"),
    }
    response = requests.post(url, headers=headers, data=data, files=files, timeout=300)

response.raise_for_status()
result = response.json()
b64_json = result["data"][0]["b64_json"]
```

## Tamaños recomendados

| `size`      | Proporción | Uso                                                                  |
| ----------- | ---------- | -------------------------------------------------------------------- |
| `auto`      | Automática | Selección automática del tamaño                                      |
| `1024x1024` | `1:1`      | Imágenes cuadradas, avatares, portadas y recursos                    |
| `1536x1024` | `3:2`      | Pósteres horizontales, banners y escenas                             |
| `1024x1536` | `2:3`      | Portadas móviles y pósteres verticales                               |
| `1536x1152` | `4:3`      | Imágenes horizontales estándar, productos y gráficos de contenido    |
| `1152x1536` | `3:4`      | Imágenes verticales estándar, portadas móviles y pósteres verticales |
| `2048x2048` | `1:1`      | Imágenes cuadradas de alta resolución                                |
| `2048x1152` | `16:9`     | Imágenes horizontales de alta resolución                             |
| `3840x2160` | `16:9`     | Imágenes horizontales 4K                                             |
| `2160x3840` | `9:16`     | Imágenes verticales 4K                                               |

`size` representa la proporción y el nivel de tamaño esperados. El servidor puede asignar o ajustar los píxeles devueltos. Usa las dimensiones de la imagen decodificada en lugar de recortar la salida por la fuerza al valor solicitado.

## Guarda la imagen

Una respuesta correcta sigue la estructura de imagen compatible con OpenAI:

```json theme={null}
{
  "created": 1710000000,
  "data": [
    {
      "b64_json": "iVBORw0KGgoAAAANSUhEUgAA...(truncated)"
    }
  ]
}
```

Lee `data[0].b64_json` y guárdalo como contenido de imagen en base64. Define siempre `output_format: "png"` para poder guardar la imagen decodificada como `.png`.

## Flujo de respuesta

Este endpoint es síncrono. Después de enviar `POST /images/edits`, mantén abierta la solicitud HTTP hasta que responda el servidor. Cuando la generación se completa, el contenido de la imagen se devuelve en `data[0].b64_json`.

El endpoint no devuelve un `task_id`, y no existe un endpoint separado para consultar el estado o descargar el resultado.

## Documentación relacionada

* [De texto a imagen](/es/api-reference/images-generations)
* [GPT Image 2 ya está disponible](/es/model-updates/gpt-image-2)


## OpenAPI

````yaml api-reference/openapi.json POST /v1/images/edits
openapi: 3.1.0
info:
  title: BetterToken GPT Image 2 API
  description: >-
    OpenAI-compatible image generation and image editing endpoints for
    BetterToken.
  version: 1.0.0
servers:
  - url: https://www.bettertoken.ai
security:
  - bearerAuth: []
paths:
  /v1/images/edits:
    post:
      tags:
        - GPT Image 2
      summary: 图生图（图片编辑）
      description: >-
        使用 GPT Image 2 根据一张或多张参考图片生成新图片。请求使用 multipart/form-data，成功响应中的图片内容位于
        data[0].b64_json。
      operationId: createImageEdit
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/ImageToImageRequest'
            encoding:
              image:
                contentType: image/png, image/jpeg, image/webp
              image[]:
                contentType: image/png, image/jpeg, image/webp
            example:
              model: YOUR_MODEL_ID
              prompt: 参考这张图片，生成一张更精致的方形产品主视觉，保持主体风格一致。
              'n': '1'
              size: 1024x1024
              response_format: b64_json
              output_format: png
      responses:
        '200':
          $ref: '#/components/responses/ImageResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '402':
          $ref: '#/components/responses/PaymentRequired'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/ServerError'
      x-codeSamples:
        - lang: cURL
          label: cURL single image
          source: |-
            curl 'https://www.bettertoken.ai/v1/images/edits' \
              -H 'Authorization: Bearer YOUR_API_KEY' \
              -F 'model=YOUR_MODEL_ID' \
              -F 'prompt=参考这张图片，生成一张更精致的方形产品主视觉，保持主体风格一致。' \
              -F 'n=1' \
              -F 'size=1024x1024' \
              -F 'response_format=b64_json' \
              -F 'output_format=png' \
              -F 'image=@reference.png'
        - lang: cURL
          label: cURL multiple images
          source: |-
            curl 'https://www.bettertoken.ai/v1/images/edits' \
              -H 'Authorization: Bearer YOUR_API_KEY' \
              -F 'model=YOUR_MODEL_ID' \
              -F 'prompt=综合这些参考图，生成一张统一风格的宣传海报。' \
              -F 'n=1' \
              -F 'size=1024x1024' \
              -F 'response_format=b64_json' \
              -F 'output_format=png' \
              -F 'image[]=@reference-1.png' \
              -F 'image[]=@reference-2.jpg' \
              -F 'image[]=@reference-3.png'
components:
  schemas:
    ImageToImageRequest:
      type: object
      required:
        - model
        - prompt
      properties:
        model:
          type: string
          description: 固定使用 YOUR_MODEL_ID。
          enum:
            - YOUR_MODEL_ID
          default: YOUR_MODEL_ID
          example: YOUR_MODEL_ID
        prompt:
          type: string
          description: 图片编辑或参考图生成说明。
          example: 参考这张图片，生成一张更精致的方形产品主视觉，保持主体风格一致。
        image:
          type: string
          format: binary
          description: 单张参考图字段名。单参考图时使用 image。
        image[]:
          type: array
          description: 多张参考图字段名。多参考图时重复提交 image[]。
          items:
            type: string
            format: binary
        'n':
          oneOf:
            - type: integer
            - type: string
          description: 推荐固定为 1。多张图片建议发起多次独立请求。
          default: '1'
          example: '1'
        size:
          $ref: '#/components/schemas/ImageSize'
        response_format:
          type: string
          description: 推荐固定为 b64_json。
          enum:
            - b64_json
          default: b64_json
          example: b64_json
        output_format:
          type: string
          description: 推荐固定为 png。不要依赖 jpeg 或 webp 直接返回对应格式。
          enum:
            - png
          default: png
          example: png
      additionalProperties: false
    ImageSize:
      type: string
      description: >-
        图片尺寸和比例档位。auto 为自动；1024x1024 和 2048x2048 为 1:1；1536x1024 为 3:2；1024x1536
        为 2:3；1536x1152 为 4:3；1152x1536 为 3:4；2048x1152 和 3840x2160 为
        16:9；2160x3840 为 9:16。实际返回像素可能由服务端映射或调整，客户端应以解码后的真实图片尺寸为准。
      enum:
        - auto
        - 1024x1024
        - 1536x1024
        - 1024x1536
        - 1536x1152
        - 1152x1536
        - 2048x2048
        - 2048x1152
        - 3840x2160
        - 2160x3840
      default: 1024x1024
      example: 1024x1024
    ImageResponse:
      type: object
      description: >-
        OpenAI-compatible image response. Clients should read data[0].b64_json
        and allow additional fields such as revised_prompt.
      properties:
        created:
          type: integer
          example: 1710000000
        data:
          type: array
          items:
            type: object
            properties:
              b64_json:
                type: string
                description: Base64-encoded image content.
                example: iVBORw0KGgoAAAANSUhEUgAA...(truncated)
              revised_prompt:
                type: string
                description: Optional revised prompt.
            additionalProperties: true
      additionalProperties: true
    ErrorResponse:
      type: object
      properties:
        error:
          type: object
          properties:
            message:
              type: string
              example: invalid request
            type:
              type: string
              example: invalid_request_error
            code:
              type: string
              example: invalid_request
          additionalProperties: true
        message:
          type: string
          example: insufficient quota
      additionalProperties: true
  responses:
    ImageResponse:
      description: Image generation result.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ImageResponse'
          example:
            created: 1710000000
            data:
              - b64_json: iVBORw0KGgoAAAANSUhEUgAA...(truncated)
    BadRequest:
      description: 请求格式错误、缺少参数、JSON 或 multipart 解析失败、尺寸格式错误。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Unauthorized:
      description: API Key 缺失或无效。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    PaymentRequired:
      description: 额度或余额不足。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    RateLimited:
      description: 触发限速、并发限制或上游繁忙。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    ServerError:
      description: 网关或上游服务异常。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: BetterToken API Key
      description: >-
        Use your BetterToken API Key as a bearer token. Do not expose API keys
        in frontend browser code, screenshots, logs, tickets, or Git
        repositories.

````