# 画像編集

指示や領域指定による画像編集、背景置換、縦横比変更、配色変更、文字置換を行います。

出典：https://scifig.ai/ja/docs/api/image-edits

## 操作

JSON 本文を伴う `POST /images/edits`。必要なスコープ：`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`（`#RRGGBB` 1～8 色。省略時は自動選択）、`quality` | 50 / 75 / 100 |
| replace_text | フォントと位置を保ちながら文字ラベルを置換 | `text_detection`, `replacements` | 100 |

マスクは、用途 `mask` でアップロードする PNG です。画像と同じサイズで、変更できる領域を白で示します。領域編集は `quality` の指定にかかわらず常に `premium` モデルを使用します。`replace_text` は `quality` を受け付けず、常に文字編集モデルを使用し、`premium` 料金が適用されます。

## 文字の置換

- 同じ画像で [`POST /images/text-detections`](/ja/docs/api/text-detections) を呼び出します。無料で、`id` と、それぞれに `index` を持つ `texts` を返します。
- `operation: "replace_text"`、`text_detection: <id>`、`replacements: [{"index": 0, "text": "Figure 1"}]` を送信します。指定しなかった文字は変更されません。
- 検出結果にないインデックスを指定すると、`details.reason = TEXT_INDEX_OUT_OF_RANGE` 付きの `400 INVALID_REQUEST` を返し、課金しません。

## クレジット

ジョブ作成時にクレジットを確保し、成功時に一度だけ課金し、失敗時には全額返還します。レスポンスはジョブです。フィールドとステータスは[ジョブと待機時間の上限](/ja/docs/api/jobs)、エラーは[エラー](/ja/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())
```
