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

# Text to Image

> Krea API의 텍스트-투-이미지 모델(Krea 2, Flux, Nano Banana Pro 등)을 요금, 기능, 코드 샘플과 함께 비교하여 적합한 모델을 선택하세요.

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-text-to-image.webp" title="Text to Image" description="텍스트 프롬프트로부터 고품질 이미지를 생성합니다. 최첨단 AI 모델을 사용해 사실적인 이미지부터 예술적인 일러스트까지 무엇이든 만들어 보세요." />

## 인기 모델

<div className="grid grid-cols-1 md:grid-cols-2 gap-4 hidden dark:grid">
  <ModelOverviewCard name="Krea 2" href="/developers/krea-2/overview" icon="/images/logo/krea-logo-icon-dark.svg" description="Krea의 파운데이션 모델 — 스타일 전이, 무드보드, 조절 가능한 크리에이티비티." />

  <ModelOverviewCard name="Flux" href="/api-reference/image/flux" icon="/images/logo/bfl-dark.svg" description="다양한 스타일 지원과 커스텀 비율을 갖춘 빠르고 다재다능한 생성 모델." />

  <ModelOverviewCard name="Nano Banana Pro" href="/api-reference/image/nano-banana-pro" icon="/images/logo/deepmind-dark.svg" description="탁월한 타이포그래피와 사실적 디테일을 갖춘 Google 최신 모델." />

  <ModelOverviewCard name="Seedream 4" href="/api-reference/image/seedream-4" icon="/images/logo/bytedance-dark.svg" description="사실적인 디테일과 유연한 해상도를 지원하는 고품질 텍스트-투-이미지 및 이미지-투-이미지 모델." />

  <ModelOverviewCard name="GPT Image 2" href="/api-reference/image/chatgpt-2" icon="/images/logo/openai-dark.svg" description="고품질 생성 및 편집을 위한 OpenAI의 최신 이미지 모델." />
</div>

<div className="grid grid-cols-1 md:grid-cols-2 gap-4 block dark:hidden">
  <ModelOverviewCard name="Krea 2" href="/developers/krea-2/overview" icon="/images/logo/krea-logo-icon-light.svg" description="Krea의 파운데이션 모델 — 스타일 전이, 무드보드, 조절 가능한 크리에이티비티." />

  <ModelOverviewCard name="Flux" href="/api-reference/image/flux" icon="/images/logo/bfl-light.svg" description="다양한 스타일 지원과 커스텀 비율을 갖춘 빠르고 다재다능한 생성 모델." />

  <ModelOverviewCard name="Nano Banana Pro" href="/api-reference/image/nano-banana-pro" icon="/images/logo/deepmind-light.svg" description="탁월한 타이포그래피와 사실적 디테일을 갖춘 Google 최신 모델." />

  <ModelOverviewCard name="Seedream 4" href="/api-reference/image/seedream-4" icon="/images/logo/bytedance-light.svg" description="사실적인 디테일과 유연한 해상도를 지원하는 고품질 텍스트-투-이미지 및 이미지-투-이미지 모델." />

  <ModelOverviewCard name="GPT Image 2" href="/api-reference/image/chatgpt-2" icon="/images/logo/openai-light.svg" description="고품질 생성 및 편집을 위한 OpenAI의 최신 이미지 모델." />
</div>

***

## 개요

Flux, Nano Banana Pro를 비롯한 최첨단 AI 모델을 사용해 텍스트 설명으로부터 이미지를 생성합니다. 이 예시는 생성 요청 전송부터 최종 이미지 수신까지의 전체 워크플로우를 안내합니다.

<Note>
  이미지 생성은 비동기적으로 이루어집니다. 즉시 작업 ID를 받게 되며, 이미지가 준비될 때까지 폴링을 통해 결과를 확인합니다.
</Note>

## 인터랙티브 플레이그라운드

다양한 언어로 작성된 전체 예시입니다:

<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 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={null}
  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={null}
  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={null}
  # 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"
  ```
</CodeGroup>

<Info>
  **API 토큰으로 교체하세요**

  위 예시의 YOUR\_API\_TOKEN 플레이스홀더를 교체하려면 [krea.ai/settings/api-tokens](https://www.krea.ai/settings/api-tokens)에서 API 토큰을 생성해야 합니다. 도움이 필요하다면 [API Keys & Billing](/developers/api-keys-and-billing) 페이지의 안내를 따르세요.
</Info>

사용 가능한 모든 모델을 확인하려면 [Model APIs](/api-reference/introduction) 페이지를 참고하세요.

***

## 상세 설명

아래에서는 생성 요청 전송부터 최종 이미지 수신까지의 전체 워크플로우를 단계별로 안내합니다.

## 1단계: 이미지 생성 작업 만들기

프롬프트와 파라미터를 담아 `/generate/image/bfl/flux-1-dev`로 POST 요청을 보냅니다. API는 즉시 작업 ID를 반환하며, 생성은 비동기적으로 진행됩니다.

<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("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={null}
  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={null}
  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={null}
  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"])
  }
  ```
</CodeGroup>

**예시 응답**

```json theme={null}
{
  "job_id": "550e8400-e29b-41d4-a716-446655440000",
  "status": "queued",
  "created_at": "2025-01-15T10:30:00.000Z"
}
```

***

## 2단계: 결과 폴링하기

작업이 완료될 때까지 `/jobs/{job_id}`를 2초마다 폴링하세요. Krea API는 일부 모델에 대해 중간 생성 결과를 제공합니다.

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

<Note>
  **웹훅을 사용할 수 있습니다!**

  작업이 완료될 때 알림을 받으려면 웹훅을 설정하세요. 시작하려면 [Webhooks 가이드](/developers/webhooks)를 참고하세요.
</Note>

<Tip>
  모든 모델의 자세한 파라미터 목록은 [Model APIs](/api-reference/introduction) 페이지를 확인하세요.
</Tip>

**완료된 응답 예시**

```json theme={null}
{
  "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](/developers/job-lifecycle) 페이지를 확인하세요.
</Tip>
