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

# 图生图

> 对比 Krea API 上的图生图模型，如 Flux、Nano Banana Pro 和 Seedream，用于图像放大、风格迁移、画质增强和变体生成，支持托管图片 URL 与 base64 data URI 输入，并附各模型的定价、能力说明和代码示例，帮助你快速完成模型选型与接入。

![](https://s.krea.ai/docs-image-to-image.webp)

# 图生图

使用图生图生成完成各类任务,例如放大、风格迁移、图像增强以及生成图像变体。

# 图生图

使用图生图生成完成各类任务,例如放大、风格迁移、图像增强以及生成图像变体。

## 热门模型

Flux logo

### [Flux](https://www.krea.ai/docs/api-reference/image/flux)

快速、灵活的生成能力,支持广泛的风格与自定义比例。

Nano Banana Pro logo

### [Nano Banana Pro](https://www.krea.ai/docs/api-reference/image/nano-banana-pro.md)

Google 最新模型,具备出色的排版能力和逼真的细节表现。

Seedream 4 logo

### [Seedream 4](https://www.krea.ai/docs/api-reference/image/seedream-4.md)

高质量的图生图与文生图,逼真的细节与灵活的分辨率。

GPT Image 2 logo

### [GPT Image 2](https://www.krea.ai/docs/api-reference/image/chatgpt-2.md)

OpenAI 最新的图像模型,可用于高质量生成与编辑。

***

## 第 1 步:上传或引用图像

首先,您需要提供源图像。您可以选择:

* 以 base64 数据 URI 的形式上传图像文件。
* 提供可公开访问的图像 URL。

```javascript Node.js theme={"theme":{"light":"github-light-default","dark":"vesper"}}
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={"theme":{"light":"github-light-default","dark":"vesper"}}
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"
```

> [!NOTE]
>
> **替换为您的 API Token**
>
> 要替换上述示例中的 YOUR\_API\_TOKEN 占位符,您需要在 [krea.ai/settings/api-tokens](https://www.krea.ai/settings/api-tokens) 生成一个 API token。如需帮助,请参阅 [API 密钥与计费](https://www.krea.ai/docs/developers/api-keys-and-billing.md)页面。

***

## 第 2 步:生成图像

携带您的图像和参数,向相应端点发起 POST 请求。

```javascript Node.js theme={"theme":{"light":"github-light-default","dark":"vesper"}}
// 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={"theme":{"light":"github-light-default","dark":"vesper"}}
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={"theme":{"light":"github-light-default","dark":"vesper"}}
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={"theme":{"light":"github-light-default","dark":"vesper"}}
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"])
}
```

**响应示例**

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

***

## 第 3 步:轮询结果

图像生成是异步进行的。您会立即收到一个任务 ID,随后通过轮询获取结果,直到图像准备就绪。每 2 秒轮询一次 `/jobs/{job_id}`,直到任务完成。

```javascript Node.js theme={"theme":{"light":"github-light-default","dark":"vesper"}}
// 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={"theme":{"light":"github-light-default","dark":"vesper"}}
curl -X GET https://api.krea.ai/jobs/YOUR_JOB_ID \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

```python Python theme={"theme":{"light":"github-light-default","dark":"vesper"}}
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={"theme":{"light":"github-light-default","dark":"vesper"}}
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)
    }
}
```

**已完成响应示例**

```json theme={"theme":{"light":"github-light-default","dark":"vesper"}}

{
  "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]
>
> **支持 Webhook!**
>
> 设置 Webhook 即可在任务完成时收到通知。请参阅 [Webhooks 指南](https://www.krea.ai/docs/developers/webhooks.md)开始使用。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.