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

# Trasformare immagini (img2img)

> Invia un job img2img — 1–14 immagini di riferimento più un prompt — e ottieni un id del job.

Trasforma 1–14 `images` sorgente con un `prompt`. La chiamata restituisce
**`202 Accepted`** con un `id` del job; interroga
[`GET /images/img2img/{id}`](/it/api-reference/image-ops/get-img2img) per il
risultato. Ogni voce in `images` è un oggetto sorgente che prende **esattamente uno**
tra `image_id`, `url` o `base64` + `mime_type`; l'ordine è preservato. Richiede lo
scope `images.edit`.

## Esempio: una sorgente per modalità

<CodeGroup>
  ```bash image_id theme={null}
  curl -X POST https://api.samsa.ai/public/v1/images/img2img \
    -H "Authorization: Bearer $SAMSA_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "images": [{ "image_id": "123e4567-e89b-12d3-a456-426614174000" }],
      "prompt": "Place the product on a marble kitchen counter"
    }'
  ```

  ```bash url theme={null}
  curl -X POST https://api.samsa.ai/public/v1/images/img2img \
    -H "Authorization: Bearer $SAMSA_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "images": [{ "url": "https://cdn.example.com/photo.png" }],
      "prompt": "Turn this sketch into a photorealistic render",
      "resolution": "2K"
    }'
  ```

  ```bash base64 theme={null}
  curl -X POST https://api.samsa.ai/public/v1/images/img2img \
    -H "Authorization: Bearer $SAMSA_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "images": [{ "base64": "iVBORw0KGgoAAAANSUhEUg...", "mime_type": "image/png" }],
      "prompt": "Apply a warm sunset color grade",
      "num_outputs": 2
    }'
  ```
</CodeGroup>

## Esempio: combinare più sorgenti

Passa più sorgenti — mescolare le modalità è consentito — e regola engine, rapporto e
risoluzione:

```json Body theme={null}
{
  "images": [
    { "image_id": "123e4567-e89b-12d3-a456-426614174000" },
    { "url": "https://cdn.example.com/reference.jpg" },
    { "base64": "iVBORw0KGgoAAAANSUhEUg...", "mime_type": "image/webp" }
  ],
  "prompt": "Blend the subject into the reference scene",
  "engine": "nano_banana_2",
  "aspect_ratio": "16:9",
  "resolution": "4K",
  "webhook_url": "https://example.com/webhooks/samsa"
}
```

La risposta `202` è l'handle del job asincrono:

```json 202 Accepted theme={null}
{
  "id": "b3f1c2d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
  "status": "pending",
  "estimated_credits": 20
}
```

<Note>
  `images` contiene 1–14 sorgenti; ognuna è **esattamente una** tra `image_id`, un
  `url` https o `base64` + `mime_type`. `prompt` è obbligatorio. `engine` è
  `nano_banana_pro` (predefinito) o `nano_banana_2`; un engine sconosciuto
  restituisce `422`. `aspect_ratio` è validato rispetto all'elenco supportato
  dall'engine (`1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`,
  `21:9`; `nano_banana_2` inoltre `4:1`, `1:4`, `8:1`, `1:8`); se omesso, preserva la
  forma della sorgente. `resolution` è `1K` (predefinito), `2K` o `4K`.
  `num_outputs` (1–4) è **1** per impostazione predefinita e ogni output viene
  addebitato. `output_format` è solo `png` in v1.
</Note>

## Credits

Ogni output costa `5` credits a `1K`, con scalatura in base alla risoluzione
(`1K` ×1, `2K` ×2, `4K` ×4) e moltiplicato per `num_outputs`. Vedi
[Prezzi](/it/guides/pricing).

## Errori

| Stato | Codice                                                                                                                                                                                                                                   | Quando                                                                                                                                                                                                                                                                                                                                                                                             |
| ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `402` | [`insufficient_credits`](/it/guides/errors#insufficient_credits) / [`insufficient_team_credits`](/it/guides/errors#insufficient_team_credits) / [`insufficient_unallocated_credits`](/it/guides/errors#insufficient_unallocated_credits) | Il saldo che questa credenziale può spendere è al di sotto del costo del job. Le organizzazioni con almeno un team attivo ricevono i codici legati ai team invece di `insufficient_credits` (eccetto le organizzazioni di sistema esenti dal budgeting per team). Un guasto operativo nella detrazione stessa può comunque restituire il generico `insufficient_credits`, qualunque sia il regime. |
| `402` | [`subscription_inactive`](/it/guides/errors#subscription_inactive)                                                                                                                                                                       | L'organizzazione non ha un abbonamento utilizzabile.                                                                                                                                                                                                                                                                                                                                               |
| `403` | [`missing_scope`](/it/guides/errors#missing_scope)                                                                                                                                                                                       | La chiave non ha lo scope `images.edit`.                                                                                                                                                                                                                                                                                                                                                           |
| `404` | [`not_found`](/it/guides/errors#not_found)                                                                                                                                                                                               | Un `image_id` sorgente è sconosciuto o non appartiene al creatore della chiave — anche un'immagine creata da un altro membro della tua organizzazione è un `404`.                                                                                                                                                                                                                                  |
| `422` | [`validation_error`](/it/guides/errors#validation_error)                                                                                                                                                                                 | Zero/più modalità sorgente, prompt non valido, engine sconosciuto o rapporto non supportato.                                                                                                                                                                                                                                                                                                       |
| `429` | [`rate_limited`](/it/guides/errors#rate_limited) / [`too_many_active_jobs`](/it/guides/errors#too_many_active_jobs)                                                                                                                      | Finestra di frequenza per chiave o limite di concorrenza per organizzazione superato.                                                                                                                                                                                                                                                                                                              |


## OpenAPI

````yaml api-reference/openapi.json POST /images/img2img
openapi: 3.1.0
info:
  title: Samsa API
  description: >-
    The Samsa public REST API. Authenticate with an organization API key as a
    bearer token (`Authorization: Bearer samsa_sk_...`). Errors follow a single
    envelope shape; every response carries an `X-Request-ID`.
  version: 1.0.0
servers:
  - url: https://api.samsa.ai/public/v1
security:
  - BearerAuth: []
paths:
  /images/img2img:
    post:
      tags:
        - Images
      summary: Transform reference images with a prompt (img2img)
      description: >-
        Submits an img2img job — 1-14 source `images` plus a `prompt` — and
        returns `202` immediately with the job `id` and a credit estimate; poll
        `GET /images/img2img/{id}` for the result. Each source is exactly one of
        `image_id` (an image in your organization's context), an https `url`, or
        `base64`+`mime_type`. Optional `engine` (`nano_banana_pro` default,
        `nano_banana_2`), `aspect_ratio` (validated against the engine's
        supported list; omitted = the engine preserves the source shape), and
        `resolution` (`1K` default, `2K`, `4K`). `num_outputs` defaults to
        **1**; each output is billed at `5 x resolution_multiplier` credits
        (1K:1x, 2K:2x, 4K:4x). Common errors: unknown `engine`, unsupported
        `aspect_ratio`, or a rejected `prompt` return `422`; a foreign or
        unknown `image_id` returns `404`; missing credits or no usable org
        subscription returns `402`; the per-key rate limit or per-org
        concurrency cap returns `429`. Requires the `images.edit` scope.
      operationId: create_image_img2img_images_img2img_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PublicImg2ImgRequest'
        required: true
      responses:
        '202':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PublicTransformAccepted'
        '401':
          description: Missing, invalid, expired, or revoked API key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '402':
          description: Insufficient credits, or no usable org subscription.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '403':
          description: The API key lacks the required scope for this operation.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '404':
          description: Generation, or a referenced model/palette, not found.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '409':
          description: A referenced model is not ready for generation.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '422':
          description: Request validation failed (prompt, engine, resolution, ...).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '429':
          description: Per-key rate limit or per-org concurrency cap exceeded.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '500':
          description: Internal server error.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
components:
  schemas:
    PublicImg2ImgRequest:
      properties:
        images:
          items:
            $ref: '#/components/schemas/PublicImageEditSource'
          type: array
          maxItems: 14
          minItems: 1
          title: Images
          description: >-
            1-14 source images; each exactly one of `image_id`, an https `url`,
            or `base64`+`mime_type`. Order is preserved.
        prompt:
          type: string
          minLength: 1
          title: Prompt
          description: >-
            Text prompt describing the transformation. Runs the same validation
            as the app (rejects empty / malformed / policy-violating prompts
            with a `422`).
          examples:
            - Combine the products into one cohesive lifestyle scene
        engine:
          anyOf:
            - type: string
            - type: 'null'
          title: Engine
          description: >-
            Img2img engine — one of `nano_banana_pro` (default) or
            `nano_banana_2`. Omit to use the default. Unknown engines return
            `422`.
          examples:
            - nano_banana_pro
        aspect_ratio:
          anyOf:
            - type: string
            - type: 'null'
          title: Aspect Ratio
          description: >-
            Optional aspect ratio for the generated image(s), validated against
            the engine's supported list (`1:1`, `2:3`, `3:2`, `3:4`, `4:3`,
            `4:5`, `5:4`, `9:16`, `16:9`, `21:9`; `nano_banana_2` additionally
            `4:1`, `1:4`, `8:1`, `1:8`). Omitted = the engine preserves the
            source shape.
          examples:
            - '1:1'
        resolution:
          type: string
          title: Resolution
          description: >-
            Output resolution — `1K` (default), `2K`, or `4K`. Credits scale
            1K:1x, 2K:2x, 4K:4x per output.
          default: 1K
          examples:
            - 1K
        num_outputs:
          type: integer
          maximum: 4
          minimum: 1
          title: Num Outputs
          description: >-
            Number of images to generate (1-4). Defaults to **1** (the app
            default is 4); each output is billed.
          default: 1
          examples:
            - 1
        output_format:
          $ref: '#/components/schemas/PublicImageOutputFormat'
          description: Encoding of the returned images. v1 supports `png` only.
          default: png
          examples:
            - png
        webhook_url:
          anyOf:
            - type: string
            - type: 'null'
          title: Webhook Url
          description: >-
            Optional https webhook notified once on terminal status (signed per
            the webhook signature scheme; see the webhooks docs).
          examples:
            - https://example.com/webhooks/samsa
      type: object
      required:
        - images
        - prompt
      title: PublicImg2ImgRequest
      description: >-
        `POST /images/img2img` body (SAM-815 / S8.3 — ADR §8, §10).


        Transform 1-14 source `images` with a `prompt` (the app's Edit-tab
        img2img

        flow). Each source is exactly one of `image_id` (an image in your

        organization's context), an https `url`, or `base64`+`mime_type`.
        `engine`

        is a public-safe alias of the internal edit model (`nano_banana_pro`

        default, `nano_banana_2`); `num_outputs` defaults to **1** (the app
        default

        is 4). Each output is billed at `5 x resolution_multiplier` credits

        (1K:1x, 2K:2x, 4K:4x).
      examples:
        - images:
            - image_id: 123e4567-e89b-12d3-a456-426614174000
          prompt: Place the product on a marble kitchen counter
        - images:
            - url: https://cdn.example.com/photo.png
          prompt: Turn this sketch into a photorealistic render
          resolution: 2K
        - images:
            - base64: iVBORw0KGgoAAAANSUhEUg...
              mime_type: image/png
          num_outputs: 2
          prompt: Apply a warm sunset color grade
        - aspect_ratio: '16:9'
          engine: nano_banana_2
          images:
            - image_id: 123e4567-e89b-12d3-a456-426614174000
            - url: https://cdn.example.com/reference.jpg
            - base64: iVBORw0KGgoAAAANSUhEUg...
              mime_type: image/webp
          prompt: Blend the subject into the reference scene
          resolution: 4K
          webhook_url: https://example.com/webhooks/samsa
    PublicTransformAccepted:
      properties:
        id:
          type: string
          format: uuid
          title: Id
          description: The job id — poll the op's `GET .../{id}` endpoint.
        status:
          $ref: '#/components/schemas/PublicImageStatus'
          description: >-
            Initial status: `pending` (job queued — enter the polling flow), or
            `completed` with `estimated_credits: 0` when `background-removals` /
            `vectorizations` serve an owned-image cache hit (the result is
            immediately available).
          examples:
            - pending
        estimated_credits:
          type: integer
          title: Estimated Credits
          description: >-
            Credits this job is expected to cost — `0` on a cache-hit
            `completed` response.
          examples:
            - 5
      type: object
      required:
        - id
        - status
        - estimated_credits
      title: PublicTransformAccepted
      description: >-
        Shared `202` body for the transform-op submits (SAM-813 / S8 wave).


        Every `POST /images/<op>` returns the async job handle

        `{id, status, estimated_credits}`. The initial `status` is `pending`
        (the

        job is queued), with ONE exception: `background-removals` and

        `vectorizations` answer an owned-`image_id` cache hit (a ready result

        already exists for that image) with `status: "completed"` and

        `estimated_credits: 0` — no new job is queued, the `completed` webhook

        event is emitted immediately for a supplied `webhook_url`, and the
        result

        is already available from the op's `GET .../{id}` endpoint. The other

        transform ops (`img2img`, `variations`, `resizes`, `upscales`) always

        start `pending`.
    ErrorEnvelope:
      properties:
        error:
          $ref: '#/components/schemas/ErrorDetail'
      type: object
      required:
        - error
      title: ErrorEnvelope
      description: The complete public error body — an ``error`` object wrapper (ADR §5).
    PublicImageEditSource:
      properties:
        image_id:
          anyOf:
            - type: string
              format: uuid
            - type: 'null'
          title: Image Id
          description: Id of an image in your organization's context to edit.
        url:
          anyOf:
            - type: string
            - type: 'null'
          title: Url
          description: https URL of the source image (downloaded under SSRF guards).
          examples:
            - https://cdn.example.com/photo.png
        base64:
          anyOf:
            - type: string
            - type: 'null'
          title: Base64
          description: Base64-encoded source image bytes (send with `mime_type`).
        mime_type:
          anyOf:
            - type: string
            - type: 'null'
          title: Mime Type
          description: >-
            MIME type for a base64 source — one of: image/jpeg, image/png,
            image/webp.
          examples:
            - image/png
      type: object
      title: PublicImageEditSource
      description: >-
        The source image for an edit — exactly one of three modes (ticket §1).


        * `image_id` — an image already in the key creator's context (owned by
        the key
          creator; ownership is enforced in the route -> `404` on a miss).
        * `url` — an `https` URL the server downloads under the SSRF guard
        (§7.4).

        * `base64` + `mime_type` — inline bytes (`mime_type` in the allow-list).


        Exactly one mode must be supplied; zero or more than one is a `422`.


        `url` / `base64` rasters must decode to at most **33,554,432 pixels**

        (32 MP, width x height) — a larger source returns `422` naming the
        source

        param, before any charge (same ceiling the resize op documents).
    PublicImageOutputFormat:
      type: string
      enum:
        - png
      title: PublicImageOutputFormat
      description: >-
        Public output format for generated images.


        v1 exposes ``png`` only: both public engines route through the Gemini
        path,

        which reliably returns PNG and does NOT convert to ``jpeg``/``webp`` (it
        would

        accept the request, charge, and still return PNG — a misleading
        contract). The

        other formats are deferred until the generation path converts them
        (SAM-623).
    PublicImageStatus:
      type: string
      enum:
        - pending
        - processing
        - completed
        - failed
        - cancelled
      title: PublicImageStatus
      description: >-
        Public image-job status — the lower-cased internal ``TaskStatus``.


        Deliberately the plain lower-cased internal value (NOT the ADR §7.2

        ``PENDING -> queued`` remap): the ticket's 202 uses ``status:
        "pending"`` and

        its fixtures say ``pending/processing/completed/failed``, and this keeps
        the

        public surface consistent with the already-shipped models API

        (``PublicModelStatus``).
    ErrorDetail:
      properties:
        type:
          type: string
          title: Type
          examples:
            - authentication_error
        code:
          type: string
          title: Code
          examples:
            - invalid_api_key
        message:
          type: string
          title: Message
          examples:
            - The provided API key is invalid, expired, or revoked.
        request_id:
          type: string
          title: Request Id
          examples:
            - 8f14e45fceea167a5a36dedd4bea2543
        param:
          anyOf:
            - type: string
            - type: 'null'
          title: Param
          description: Present on validation errors — names the offending field.
          examples:
            - aspect_ratio
      type: object
      required:
        - type
        - code
        - message
        - request_id
      title: ErrorDetail
      description: The ``error`` object of the public envelope (ADR §5).
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      description: >-
        Organization API key as a bearer token: `Authorization: Bearer
        samsa_sk_...`.

````