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

# Imagen a imagen

> Compara modelos de imagen a imagen en Krea para escalado, transferencia de estilo, mejora y variaciones, con soporte para URLs y entradas base64 en formato data URI.

export const ModelOverviewCard = ({name, description, icon, href}) => {
  const resolvedIcon = (() => {
    if (typeof icon !== "string" || !icon.startsWith("/") || icon.startsWith("//")) return icon;
    if (typeof window === "undefined") return icon;
    const base = "/docs";
    const under = window.location.pathname === base || window.location.pathname.startsWith(base + "/");
    return under && !icon.startsWith(base + "/") ? base + icon : icon;
  })();
  return <a href={href} className="group relative block rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-black overflow-hidden hover:border-black dark:hover:border-white transition-all duration-200 p-6">
      {}
      <div className="flex items-center justify-center w-8 h-8 rounded-lg mb-4 transition-colors duration-200">
        {icon && <img src={resolvedIcon} alt={`${name} logo`} className="w-8 h-8 object-contain transition-all duration-200" />}
      </div>

      {}
      <div className="space-y-2">
        <h3 className="text-lg font-semibold text-black dark:text-white transition-colors">
          {name}
        </h3>
        <p className="text-sm text-gray-600 dark:text-gray-400 line-clamp-4">
          {description}
        </p>
      </div>

      {}
      <div className="absolute top-6 right-6 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
        <svg className="w-4 h-4 text-black dark:text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
        </svg>
      </div>
    </a>;
};

export const HeroHeader = ({image, video, title, description}) => {
  return <div className="relative aspect-[2/1] h-[30vh] w-full rounded-lg overflow-hidden mb-8">
      {}
      {video && <video autoPlay muted loop playsInline className="absolute top-0 left-0 w-full h-full object-cover hidden md:block m-0" style={{
    zIndex: 1,
    objectPosition: "20% 20%"
  }}>
          <source src={video} type="video/webm" />
        </video>}

      {}
      <img src={image} alt="" className={`absolute top-0 left-0 m-0 w-full h-full object-cover ${video ? "md:hidden" : "block"}`} style={{
    zIndex: 1,
    objectPosition: "20% 20%"
  }} />

      {}
      <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/30 to-black/10 flex flex-col justify-end p-8 dark:hidden" style={{
    zIndex: 2
  }}>
        <h1 className="text-4xl font-bold text-white m-0 drop-shadow-[0_2px_4px_rgba(0,0,0,0.5)]">
          {title}
        </h1>
        <p className="text-lg text-white/95 mt-2 drop-shadow-[0_1px_2px_rgba(0,0,0,0.5)]">
          {description}
        </p>
      </div>

      {}
      <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-black/20 hidden dark:flex flex-col justify-end p-8" style={{
    zIndex: 2
  }}>
        <h1 className="text-4xl font-bold text-white m-0 drop-shadow-[0_2px_4px_rgba(0,0,0,0.5)]">
          {title}
        </h1>
        <p className="text-lg text-white/95 mt-2 drop-shadow-[0_1px_2px_rgba(0,0,0,0.5)]">
          {description}
        </p>
      </div>
    </div>;
};

<HeroHeader image="https://s.krea.ai/docs-image-to-image.webp" title="Imagen a imagen" description="Usa la generación de imagen a imagen para tareas como aumento de resolución, transferencia de estilo, mejora de imagen y variación de imagen. " />

## Modelos populares

<div className="grid grid-cols-1 md:grid-cols-2 gap-4 hidden dark:grid">
  <ModelOverviewCard name="Flux" href="/api-reference/image/flux" icon="/images/logo/bfl-dark.svg" description="Generación rápida y versátil con amplio soporte de estilos y relaciones de aspecto personalizadas." />

  <ModelOverviewCard name="Nano Banana Pro" href="/api-reference/image/nano-banana-pro" icon="/images/logo/deepmind-dark.svg" description="El último modelo de Google con tipografía superior y detalle fotorrealista." />

  <ModelOverviewCard name="Seedream 4" href="/api-reference/image/seedream-4" icon="/images/logo/bytedance-dark.svg" description="Imagen a imagen y texto a imagen de alta calidad, detalle fotorrealista y resolución flexible." />

  <ModelOverviewCard name="GPT Image 2" href="/api-reference/image/chatgpt-2" icon="/images/logo/openai-dark.svg" description="El último modelo de imagen de OpenAI para generación y edición de alta calidad." />
</div>

<div className="grid grid-cols-1 md:grid-cols-2 gap-4 block dark:hidden">
  <ModelOverviewCard name="Flux" href="/api-reference/image/flux" icon="/images/logo/bfl-light.svg" description="Generación rápida y versátil con amplio soporte de estilos y relaciones de aspecto personalizadas." />

  <ModelOverviewCard name="Nano Banana Pro" href="/api-reference/image/nano-banana-pro" icon="/images/logo/deepmind-light.svg" description="El último modelo de Google con tipografía superior y detalle fotorrealista." />

  <ModelOverviewCard name="Seedream 4" href="/api-reference/image/seedream-4" icon="/images/logo/bytedance-light.svg" description="Imagen a imagen y texto a imagen de alta calidad, detalle fotorrealista y resolución flexible." />

  <ModelOverviewCard name="GPT Image 2" href="/api-reference/image/chatgpt-2" icon="/images/logo/openai-light.svg" description="El último modelo de imagen de OpenAI para generación y edición de alta calidad." />
</div>

***

## Paso 1: Sube o referencia una imagen

Primero, debes proporcionar la imagen de origen. Puedes:

* Subir un archivo de imagen como un URI de datos base64.
* Proporcionar una URL de imagen accesible públicamente.

<CodeGroup>
  ```javascript Node.js theme={null}
  import { readFileSync } from "node:fs";

  // Option 1: Using a base64 data URI
  const imageBuffer = readFileSync("input_image.jpg");
  const imageDataUri = `data:image/jpeg;base64,${imageBuffer.toString("base64")}`;

  // Option 2: Using image URL
  const imageUrl = "https://s.krea.ai/logo-icon-black.jpg";
  ```

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

  API_BASE = "https://api.krea.ai"
  API_TOKEN = "YOUR_API_TOKEN"

  # Option 1: Using a base64 data URI
  with open("input_image.jpg", "rb") as image_file:
      image_data_uri = f"data:image/jpeg;base64,{base64.b64encode(image_file.read()).decode('utf-8')}"

  # Option 2: Using image URL
  image_url = "https://s.krea.ai/logo-icon-black.jpg"
  ```
</CodeGroup>

<Info>
  **Reemplaza con tu token de API**

  Para reemplazar el marcador YOUR\_API\_TOKEN en los ejemplos anteriores, debes generar un token de API en [krea.ai/settings/api-tokens](https://www.krea.ai/settings/api-tokens). Sigue las instrucciones en la página [Claves de API y facturación](/developers/api-keys-and-billing) si necesitas ayuda.
</Info>

***

## Paso 2: Genera la imagen

Realiza una solicitud POST al endpoint apropiado con tu imagen y parámetros.

<CodeGroup>
  ```javascript Node.js theme={null}
  // npm install @krea-ai/sdk
  import { Krea } from "@krea-ai/sdk";

  const krea = new Krea({ apiKey: process.env.KREA_API_KEY });

  const job = await krea.image("google/nano-banana-pro", {
    image_urls: [imageDataUri],
    prompt: "Turn this logo into an aesthetic rug. Product Photography style, with an aura that would make me want it in my own living room."
  });

  console.log(`Job ID: ${job.job_id}`);
  ```

  ```bash cURL theme={null}
  IMAGE_DATA_URI="data:image/jpeg;base64,$(base64 < ./input_image.jpg | tr -d '\n')"

  curl -X POST https://api.krea.ai/generate/image/google/nano-banana-pro \
    -H "Authorization: Bearer YOUR_API_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "image_urls": ["'"$IMAGE_DATA_URI"'"],
      "prompt": "Turn this logo into an aesthetic rug. Product Photography style, with an aura that would make me want it in my own living room."
    }'
  ```

  ```python Python theme={null}
  response = requests.post(
      f"{API_BASE}/generate/image/google/nano-banana-pro",
      headers={
          "Authorization": f"Bearer {API_TOKEN}",
          "Content-Type": "application/json"
      },
      json={
          "image_urls": [image_data_uri],
          "prompt": "Turn this logo into an aesthetic rug. Product Photography style, with an aura that would make me want it in my own living room.",
      }
  )

  job = response.json()
  print(f"Job ID: {job['job_id']}")
  ```

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

  import (
      "bytes"
      "encoding/base64"
      "encoding/json"
      "fmt"
      "net/http"
      "os"
  )

  func main() {
      apiBase := "https://api.krea.ai"
      apiToken := "YOUR_API_TOKEN"

      imageBytes, _ := os.ReadFile("input_image.jpg")
      imageDataURI := "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(imageBytes)

      payload := map[string]interface{}{
          "image_urls": []interface{}{imageDataURI},
          "prompt": "Turn this logo into an aesthetic rug. Product Photography style, with an aura that would make me want it in my own living room.",
      }

      jsonData, _ := json.Marshal(payload)
      req, _ := http.NewRequest("POST", apiBase+"/generate/image/google/nano-banana-pro", bytes.NewBuffer(jsonData))
      req.Header.Set("Authorization", "Bearer "+apiToken)
      req.Header.Set("Content-Type", "application/json")

      client := &http.Client{}
      resp, _ := client.Do(req)
      defer resp.Body.Close()

      var job map[string]interface{}
      json.NewDecoder(resp.Body).Decode(&job)
      fmt.Printf("Job ID: %s\n", job["job_id"])
  }
  ```
</CodeGroup>

**Respuesta de ejemplo**

```json theme={null}
{
  "created_at":"2026-02-13T02:20:58.265Z",
  "completed_at":null,
  "job_id":"757a315b-b3ed-457b-b1ba-cff5e140cfd4",
  "status":"processing",
  "type":"externalImage",
  "result":{}
}
```

***

## Paso 3: Consulta los resultados

La generación de imágenes es asíncrona. Recibirás un ID de trabajo de inmediato y luego consultarás los resultados hasta que la imagen esté lista. Consulta `/jobs/{job_id}` cada 2 segundos hasta que el trabajo se complete.

<CodeGroup>
  ```javascript Node.js theme={null}
  // npm install @krea-ai/sdk
  import { Krea } from "@krea-ai/sdk";

  const krea = new Krea({ apiKey: process.env.KREA_API_KEY });

  async function waitForJob(jobId) {
    const completed = await krea.jobs.wait(jobId, { intervalMs: 2000 });
    return completed.result.urls[0];
  }

  const imageUrl = await waitForJob(job.job_id);
  console.log(`Image ready: ${imageUrl}`);
  ```

  ```bash cURL theme={null}
  curl -X GET https://api.krea.ai/jobs/YOUR_JOB_ID \
    -H "Authorization: Bearer YOUR_API_TOKEN"
  ```

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

  def wait_for_job(job_id):
      while True:
          response = requests.get(
              f"{API_BASE}/jobs/{job_id}",
              headers={"Authorization": f"Bearer {API_TOKEN}"}
          )
          job = response.json()

          if job["status"] == "completed":
              return job["result"]["urls"][0]
          if job["status"] in ("failed", "cancelled"):
              raise Exception(f"Job failed: {job['status']}")

          print(f"Status: {job['status']}")
          time.sleep(2)

  image_url = wait_for_job(job["job_id"])
  print(f"Image ready: {image_url}")
  ```

  ```go Go theme={null}
  func waitForJob(jobID string) (string, error) {
      for {
          req, _ := http.NewRequest("GET", apiBase+"/jobs/"+jobID, nil)
          req.Header.Set("Authorization", "Bearer "+apiToken)

          resp, _ := client.Do(req)
          var job map[string]interface{}
          json.NewDecoder(resp.Body).Decode(&job)
          resp.Body.Close()

          switch job["status"] {
          case "completed":
              result := job["result"].(map[string]interface{})
              urls := result["urls"].([]interface{})
              return urls[0].(string), nil
          case "failed", "cancelled":
              return "", fmt.Errorf("job failed: %s", job["status"])
          }

          fmt.Printf("Status: %s\n", job["status"])
          time.Sleep(2 * time.Second)
      }
  }
  ```
</CodeGroup>

**Respuesta completada de ejemplo**

```json theme={null}

{
  "created_at":"2026-02-13T02:20:58.265Z",
  "completed_at":"2026-02-13T02:21:21.948Z",
  "job_id":"757a315b-b3ed-457b-b1ba-cff5e140cfd4",
  "status":"completed",
  "type":"externalImage",
  "result": {
    "urls": [
      "https://app-uploads.krea.ai/public/757a315b-b3ed-457b-b1ba-cff5e140cfd4-image.png"
    ]
  }
}
```

<Note>
  **¡Webhooks disponibles!**

  Configura webhooks para recibir notificaciones cuando los trabajos se completen. Consulta la [guía de Webhooks](/developers/webhooks) para empezar.
</Note>
