> ## 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 文生图模型 — Krea 3、Krea 2、Flux 等 — 包含定价、功能和代码示例，帮助你选择合适的模型。

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

# Text to Image

Generate high-quality images from text prompts. Create anything from photorealistic images to artistic illustrations with state-of-the-art AI models.

# Text to Image

Generate high-quality images from text prompts. Create anything from photorealistic images to artistic illustrations with state-of-the-art AI models.

## 热门模型

Krea 3 logo

### [Krea 3](https://www.krea.ai/docs/developers/krea-3/overview.md)

Krea 最新的图像模型 — 原生 2K 下的快速生成与编辑。

Krea 2 logo

### [Krea 2](https://www.krea.ai/docs/developers/krea-2/overview.md)

Krea's foundation model — style transfer, moodboards, and tunable creativity.

Flux logo

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

Fast, versatile generation with extensive style support and custom ratios.

Nano Banana Pro logo

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

Google's latest model with superior typography and photorealistic detail.

Seedream 4 logo

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

High quality text-to-image and image-to-image, photorealistic detail and flexible resolution.

GPT Image 2 logo

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

OpenAI's latest image model for high-quality generation and editing.

***

## 概述

使用 Flux、Nano Banana Pro 以及其他前沿 AI 模型，从文本描述生成图像。本示例将带你完成从提交生成请求到获取最终图像的完整流程。

> [!NOTE]
>
> 图像生成是异步的。你会立即收到一个 job ID，然后需要轮询结果，直到图像生成完成。

## 交互式 Playground

以下是不同语言的完整示例：

```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 result = await krea.subscribe("image/bfl/flux-1-dev", {
  input: {
    prompt: "a serene mountain landscape at sunset",
    width: 1024,
    height: 576,
    steps: 28
  }
});

console.log(`Image ready: ${result.data?.urls[0]}`);
```

```python Python theme={"theme":{"light":"github-light-default","dark":"vesper"}}
import requests
import time

API_BASE = "https://api.krea.ai"
API_TOKEN = "your-token-secret"

# Step 1: Create generation job
response = requests.post(
    f"{API_BASE}/generate/image/bfl/flux-1-dev",
    headers={
        "Authorization": f"Bearer {API_TOKEN}",
        "Content-Type": "application/json"
    },
    json={
        "prompt": "a serene mountain landscape at sunset",
        "width": 1024,
        "height": 576,
        "steps": 28
    }
)
job = response.json()
job_id = job["job_id"]

# Step 2: Poll for completion
while True:
    response = requests.get(
        f"{API_BASE}/jobs/{job_id}",
        headers={"Authorization": f"Bearer {API_TOKEN}"}
    )
    job = response.json()

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

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

```go Go theme={"theme":{"light":"github-light-default","dark":"vesper"}}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

func main() {
    apiBase := "https://api.krea.ai"
    apiToken := "your-token-secret"
    client := &http.Client{}

    // Step 1: Create generation job
    payload := map[string]interface{}{
        "prompt": "a serene mountain landscape at sunset",
        "width":  1024,
        "height": 576,
        "steps":  28,
    }
    jsonData, _ := json.Marshal(payload)

    req, _ := http.NewRequest("POST", apiBase+"/generate/image/bfl/flux-1-dev", bytes.NewBuffer(jsonData))
    req.Header.Set("Authorization", "Bearer "+apiToken)
    req.Header.Set("Content-Type", "application/json")

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

    jobID := job["job_id"].(string)

    // Step 2: Poll for completion
    for {
        req, _ := http.NewRequest("GET", apiBase+"/jobs/"+jobID, nil)
        req.Header.Set("Authorization", "Bearer "+apiToken)

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

        switch jobStatus["status"] {
        case "completed":
            result := jobStatus["result"].(map[string]interface{})
            imageURL := result["urls"].([]interface{})[0].(string)
            fmt.Printf("Image ready: %s\n", imageURL)
            return
        case "failed", "cancelled":
            fmt.Printf("Job failed: %s\n", jobStatus["status"])
            return
        }

        fmt.Printf("Status: %s\n", jobStatus["status"])
        time.Sleep(2 * time.Second)
    }
}
```

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
# Step 1: Create generation job
curl -X POST https://api.krea.ai/generate/image/bfl/flux-1-dev \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "a serene mountain landscape at sunset",
    "width": 1024,
    "height": 576,
    "steps": 28
  }'

# Response: {"job_id": "550e8400-e29b-41d4-a716-446655440000", ...}

# Step 2: Poll for completion (repeat until completed)
curl -X GET https://api.krea.ai/jobs/550e8400-e29b-41d4-a716-446655440000 \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

> [!NOTE]
>
> **替换为你的 API Token**
>
> 要替换上述示例中的 YOUR\_API\_TOKEN 占位符，你需要在 [krea.ai/settings/api-tokens](https://www.krea.ai/settings/api-tokens) 生成一个 API token。如果需要帮助，请参考 [API Keys & Billing](https://www.krea.ai/docs/developers/api-keys-and-billing.md) 页面上的说明。

要查看所有可用模型，请访问 [Model APIs](https://www.krea.ai/docs/api-reference/introduction.md) 页面。

***

## 分步说明

下面我们将带你完成从提交生成请求到获取最终图像的完整流程。

## 步骤 1：创建图像生成任务

向 `/generate/image/bfl/flux-1-dev` 发送 POST 请求，附带你的提示词和参数。API 会立即返回一个 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 });

const job = await krea.image("bfl/flux-1-dev", {
  prompt: "a serene mountain landscape at sunset",
  width: 1024,
  height: 576,
  steps: 28
});

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

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
curl -X POST https://api.krea.ai/generate/image/bfl/flux-1-dev \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "a serene mountain landscape at sunset",
    "width": 1024,
    "height": 576,
    "steps": 28
  }'
```

```python Python theme={"theme":{"light":"github-light-default","dark":"vesper"}}
import requests

API_BASE = "https://api.krea.ai"
API_TOKEN = "your-token-secret"

response = requests.post(
    f"{API_BASE}/generate/image/bfl/flux-1-dev",
    headers={
        "Authorization": f"Bearer {API_TOKEN}",
        "Content-Type": "application/json"
    },
    json={
        "prompt": "a serene mountain landscape at sunset",
        "width": 1024,
        "height": 576,
        "steps": 28
    }
)

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/json"
    "fmt"
    "net/http"
)

func main() {
    apiBase := "https://api.krea.ai"
    apiToken := "your-token-secret"

    payload := map[string]interface{}{
        "prompt": "a serene mountain landscape at sunset",
        "width": 1024,
        "height": 576,
        "steps": 28,
    }

    jsonData, _ := json.Marshal(payload)
    req, _ := http.NewRequest("POST", apiBase+"/generate/image/bfl/flux-1-dev", 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"}}
{
  "job_id": "550e8400-e29b-41d4-a716-446655440000",
  "status": "scheduled",
  "created_at": "2025-01-15T10:30:00.000Z"
}
```

***

## 步骤 2：轮询结果

每 2 秒轮询一次 `/jobs/{job_id}`，直到任务完成。Krea API 会为部分模型提供中间生成结果。

```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"}}
# Check job status
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)
    }
}
```

> [!NOTE]
>
> **Webhook 可用！**
>
> 设置 webhook，可在任务完成时收到通知。参见 [Webhooks 指南](https://www.krea.ai/docs/developers/webhooks.md) 开始使用。

> [!TIP]
>
> 要查看所有模型的详细参数列表，请访问 [Model APIs](https://www.krea.ai/docs/api-reference/introduction.md) 页面。

**示例完成响应**

```json theme={"theme":{"light":"github-light-default","dark":"vesper"}}
{
  "job_id": "550e8400-e29b-41d4-a716-446655440000",
  "status": "completed",
  "created_at": "2025-01-15T10:30:00.000Z",
  "completed_at": "2025-01-15T10:30:25.000Z",
  "result": {
    "urls": [
      "https://krea.ai/generations/your-image.png"
    ]
  }
}
```

> [!TIP]
>
> 要了解所有可能的任务状态以及完整的任务生命周期，请查看 [Job Lifecycle](https://www.krea.ai/docs/developers/job-lifecycle.md) 页面。


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