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

# 이미지 업로드

> 이미지를 업로드하여 URL을 획득, 이미지/비디오 생성 API에서 사용

<Note>
  **문서 Playground는 파일 업로드를 지원하지 않습니다**: 아래의 cURL, Python 또는 JavaScript 코드 예제를 사용하여 테스트해 주세요.
</Note>

<Warning>
  **중요 변경사항:** 더 나은 성능과 비용 관리를 위해 생성 API에서 base64 이미지 데이터를 직접 전달하는 것은 더 이상 지원되지 않습니다. 본 API를 사용하여 이미지를 업로드하고 URL을 획득한 후 생성 API를 호출해 주세요.
</Warning>

## 왜 이미지를 먼저 업로드해야 하나요?

1. **성능 최적화** - base64 인코딩은 데이터를 33% 팽창시킵니다. 먼저 업로드하면 요청 본문 크기를 크게 줄일 수 있습니다
2. **이미지 재사용** - 한 번 업로드하면 URL을 여러 번 사용할 수 있어 중복 전송이 필요 없습니다

## 사용 흐름

```mermaid theme={null}
sequenceDiagram
    participant 클라이언트
    participant APIMart
    participant 스토리지

    클라이언트->>APIMart: POST /v1/uploads/images (이미지 파일 업로드)
    APIMart->>스토리지: 이미지 저장
    스토리지-->>APIMart: 저장 경로 반환
    APIMart-->>클라이언트: 이미지 URL 반환
    클라이언트->>APIMart: POST /v1/images/generations (이미지 URL 사용)
```

<RequestExample>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.apimart.ai/v1/uploads/images \
    --header 'Authorization: Bearer <token>' \
    --form 'file=@/path/to/your/image.jpg'
  ```

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

  # 이미지 업로드
  with open('image.jpg', 'rb') as f:
      response = requests.post(
          "https://api.apimart.ai/v1/uploads/images",
          headers={
              "Authorization": "Bearer <token>"
          },
          files={
              "file": f
          }
      )

  result = response.json()
  image_url = result['url']
  print(f"이미지 URL: {image_url}")

  # 업로드한 이미지로 생성
  response = requests.post(
      "https://api.apimart.ai/v1/images/generations",
      headers={
          "Authorization": "Bearer <token>",
          "Content-Type": "application/json"
      },
      json={
          "model": "gemini-3-pro-image-preview",
          "prompt": "이 이미지를 기반으로 변형 생성",
          "image_urls": [{"url": image_url}]
      }
  )
  ```

  ```javascript JavaScript theme={null}
  // 이미지 업로드
  const formData = new FormData();
  formData.append('file', fileInput.files[0]);

  const uploadResponse = await fetch('https://api.apimart.ai/v1/uploads/images', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer <token>'
    },
    body: formData
  });

  const uploadResult = await uploadResponse.json();
  const imageUrl = uploadResult.url;
  console.log(`이미지 URL: ${imageUrl}`);

  // 업로드한 이미지로 생성
  const genResponse = await fetch('https://api.apimart.ai/v1/images/generations', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer <token>',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'gemini-3-pro-image-preview',
      prompt: '이 이미지를 기반으로 변형 생성',
      image_urls: [{url: imageUrl}]
    })
  });
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "url": "https://upload.apimart.ai/f/image/9990000123456-a1b2c3d4-photo.jpg",
    "filename": "photo.jpg",
    "content_type": "image/jpeg",
    "bytes": 235680,
    "created_at": 1743436800
  }
  ```

  ```json 400 - 파일 필드 누락 theme={null}
  {
    "error": {
      "message": "missing or invalid file field: http: no such file",
      "type": "invalid_request_error"
    }
  }
  ```

  ```json 400 - 지원되지 않는 형식 theme={null}
  {
    "error": {
      "message": "unsupported image type: application/pdf, allowed: jpeg, png, gif, webp",
      "type": "invalid_request_error"
    }
  }
  ```

  ```json 413 - 파일 크기 초과 theme={null}
  {
    "error": {
      "message": "file size 25165824 exceeds maximum 20971520 bytes",
      "type": "invalid_request_error"
    }
  }
  ```

  ```json 429 - 요청 빈도 제한 theme={null}
  {
    "error": {
      "code": 429,
      "message": "Rate limit exceeded. Please try again later",
      "type": "rate_limit_error"
    }
  }
  ```

  ```json 500 - 업로드 실패 theme={null}
  {
    "error": {
      "message": "failed to upload image",
      "type": "server_error"
    }
  }
  ```
</ResponseExample>

## Authorizations

<ParamField header="Authorization" type="string" required>
  모든 API는 Bearer Token 인증이 필요합니다

  API Key 획득:

  [API Key 관리 페이지](https://apimart.ai/keys)에서 API Key를 획득하세요

  요청 헤더에 추가:

  ```
  Authorization: Bearer YOUR_API_KEY
  ```
</ParamField>

## Body

<ParamField body="file" type="file" required>
  이미지 파일

  지원 형식: JPEG (.jpg, .jpeg), PNG (.png), WebP (.webp), GIF (.gif)

  최대 파일 크기: 20MB
</ParamField>

## Response

<ResponseField name="url" type="string">
  이미지의 공개 접근 URL, 생성 API에서 직접 사용 가능 (72시간 유효)
</ResponseField>

<ResponseField name="filename" type="string">
  원본 파일명
</ResponseField>

<ResponseField name="content_type" type="string">
  감지된 MIME 유형, 예: `image/jpeg`
</ResponseField>

<ResponseField name="bytes" type="integer">
  파일 크기(바이트)
</ResponseField>

<ResponseField name="created_at" type="integer">
  업로드 시간의 Unix 타임스탬프(초)
</ResponseField>

## 전체 예제: 이미지 생성 워크플로우

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

API_KEY = "your-Apimart-key"
BASE_URL = "https://api.apimart.ai"

# 1단계: 참조 이미지 업로드
def upload_image(file_path):
    with open(file_path, 'rb') as f:
        response = requests.post(
            f"{BASE_URL}/v1/uploads/images",
            headers={"Authorization": f"Bearer {API_KEY}"},
            files={"file": f}
        )
    return response.json()['url']

# 2단계: 생성 작업 생성
def create_generation(image_url, prompt):
    response = requests.post(
        f"{BASE_URL}/v1/images/generations",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "model": "gemini-3-pro-image-preview",
            "prompt": prompt,
            "image_urls": [{"url": image_url}],
            "size": "16:9"
        }
    )
    return response.json()['id']

# 3단계: 작업 상태 폴링
def wait_for_result(task_id):
    while True:
        response = requests.get(
            f"{BASE_URL}/v1/images/generations/{task_id}",
            headers={"Authorization": f"Bearer {API_KEY}"}
        )
        result = response.json()

        if result['status'] == 'completed':
            return result['url']
        elif result['status'] == 'failed':
            raise Exception(f"생성 실패: {result.get('fail_reason')}")

        time.sleep(2)

# 워크플로우 실행
image_url = upload_image("reference.jpg")
print(f"이미지 업로드 완료: {image_url}")

task_id = create_generation(image_url, "이 사진을 지브리 애니메이션 스타일로 변환")
print(f"작업 생성 완료: {task_id}")

result_url = wait_for_result(task_id)
print(f"생성 완료: {result_url}")
```
