# 圖片編輯

按指令或區域編輯圖片、替換背景、調整寬高比、重新配色或替換文字。

來源：https://scifig.ai/zh-Hant/docs/api/image-edits

## 操作

`POST /images/edits` 接受 JSON 請求體。所需權限範圍：`figures:generate`。`image` 是 `file_id`（上傳檔案或此前的輸出）；`operation` 選擇編輯操作，預設為 `instruct`。網站結果工具欄也提供相同工具。

| operation | 功能 | 欄位 | 點數 |
| --- | --- | --- | --- |
| instruct | 按指令編輯整張圖片；提供遮罩時，僅重繪遮罩區域 | `instruction`（1–2,000 個字元），可選 `mask`、`quality` | 按品質為 50 / 75 / 100；提供遮罩時為 100 |
| white_background | 將背景替換為純白色（非透明背景） | `quality` | 50 / 75 / 100 |
| aspect_ratio | 將整張圖調整為新的寬高比，並延展背景 | `aspect_ratio` (`1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9`), `quality` | 50 / 75 / 100 |
| recolor | 為圖片套用配色，保留標籤顏色 | 可選 `palette`（1–8 個 `#RRGGBB` 顏色值；不提供時自動選擇配色）、`quality` | 50 / 75 / 100 |
| replace_text | 原位修改文字標籤，保留字型和位置 | `text_detection`, `replacements` | 100 |

遮罩是以 `mask` 用途上傳的 PNG，尺寸需與圖片相同，白色標記允許修改的區域。區域編輯始終使用 `premium` 模型，不受 `quality` 影響。`replace_text` 不接受 `quality`：始終使用文字編輯模型，按 `premium` 等級計費。

## 替換文字

- 對同一張圖呼叫 [`POST /images/text-detections`](/zh-Hant/docs/api/text-detections)。該操作免費，回傳 `id` 以及帶有 `index` 的 `texts`。
- 傳送 `operation: "replace_text"`、`text_detection: <id>` 和 `replacements: [{"index": 0, "text": "Figure 1"}]`。未列出的文字保持原樣。
- 識別結果中不存在的索引會回傳 `400 INVALID_REQUEST` 和 `details.reason = TEXT_INDEX_OUT_OF_RANGE`，不扣點數。

## 點數

建立任務時預留點數，成功後僅扣除一次，失敗時全額返還。響應回傳任務；欄位和狀態請參閱[任務與有限等待](/zh-Hant/docs/api/jobs)，錯誤請參閱[錯誤](/zh-Hant/docs/api/errors)。

## cURL

```bash
curl -X POST https://scifig.ai/api/v1/images/edits \
  -H "Authorization: Bearer $SCIFIG_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Prefer: wait=25" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "<file_id>",
    "operation": "aspect_ratio",
    "aspect_ratio": "16:9"
  }'
```

## JavaScript

```javascript
const response = await fetch('https://scifig.ai/api/v1/images/edits', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.SCIFIG_API_KEY}`,
    'Idempotency-Key': crypto.randomUUID(),
    Prefer: 'wait=25',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "image": "<file_id>",
    "operation": "aspect_ratio",
    "aspect_ratio": "16:9"
  }),
});
const result = await response.json();
console.log(response.status, result);
```

## Python

```python
import os
import uuid

import requests

headers = {
    "Authorization": f"Bearer {os.environ['SCIFIG_API_KEY']}",
    "Idempotency-Key": str(uuid.uuid4()),
    "Prefer": "wait=25",
}
response = requests.post(
    "https://scifig.ai/api/v1/images/edits",
    headers=headers,
    json={
        "image": "<file_id>",
        "operation": "aspect_ratio",
        "aspect_ratio": "16:9"
    },
    timeout=60,
)
print(response.status_code, response.json())
```
