Wan モデルを使用して、テキスト指示で画像を編集します。複数画像の入出力、画像融合、主題の維持、オブジェクト検出をサポートします。
クイックスタート
wan2.7-image-pro を使用して、2 つの入力画像とテキストプロンプトから編集済み画像を生成します。
プロンプト:画像 2 のグラフィティを画像 1 の車にスプレーする
入力画像 1 | 入力画像 2 | 出力画像 (wan2.7-image-pro) |
|---|---|---|
|
|
|
呼び出しを行う前に、API キーを取得し、API キーを環境変数としてエクスポートしてください。SDK を使用して呼び出しを行うには、DashScope SDK をインストールしてください。
同期呼び出し
重要DashScope Python SDK のバージョンが1.25.15以降、DashScope Java SDK のバージョンが2.22.13以降であることを確認してください。
Python
リクエスト例
import os
import base64
import mimetypes
import urllib.request
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
# 次の base_url はシンガポールリージョン用です。{WorkspaceId} をご利用の Bailian ワークスペース ID に置き換えてください。base_url はリージョンによって異なります。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください:api_key="sk-xxx"
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
api_key = os.getenv("DASHSCOPE_API_KEY")
# --- Base64 エンコーディング関数 ---
# Base64 エンコーディング形式は data:{MIME_type};base64,{base64_data} です
def encode_file(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if not mime_type or not mime_type.startswith("image/"):
raise ValueError("サポートされていない、または認識されない画像形式です")
with open(file_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
return f"data:{mime_type};base64,{encoded_string}"
"""
画像の入力方法:
以下に 3 つの画像入力方法を示します。いずれか 1 つを選択してください。
1. パブリック URL を使用 - 一般公開されている画像に適しています。
2. ローカルファイルを使用 - ローカルでの開発やテストに適しています。
3. Base64 エンコーディングを使用 - 非公開画像や暗号化伝送が必要なシナリオに適しています。
"""
# [方法 1] パブリック画像 URL を使用
image_1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"
image_2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"
# [方法 2] ローカルファイルを使用 (絶対パスと相対パスをサポート)
# image_1 = "file:///ご利用のパス/car.png"
# image_2 = "file:///ご利用のパス/paint.png"
# [方法 3] Base64 エンコードされた画像を使用
# image_1 = encode_file("/ご利用のパス/car.png")
# image_2 = encode_file("/ご利用のパス/paint.png")
message = Message(
role="user",
content=[
{"text": "画像 2 のグラフィティを画像 1 の車にスプレーする"},
{"image": image_1},
{"image": image_2},
],
)
print("----同期呼び出し、しばらくお待ちください----")
rsp = ImageGeneration.call(
model="wan2.7-image-pro",
api_key=api_key,
messages=[message],
watermark=False,
n=1,
size="2K", # wan2.7-image-pro は、テキストからの画像生成でのみ 4K 解像度をサポートします。画像編集および複数画像生成は、最大 2K の解像度をサポートします。
)
# 結果の画像 URL を抽出し、画像をローカルファイルに保存します。
if rsp.status_code == 200:
for i, choice in enumerate(rsp.output.choices):
for j, content in enumerate(choice["message"]["content"]):
if content.get("type") == "image":
image_url = content["image"]
file_name = f"output_{i}_{j}.png"
# 結果の URL は 24 時間有効です。速やかにダウンロードしてください。
urllib.request.urlretrieve(image_url, file_name)
print(f"画像が {file_name} に保存されました")
else:
print(f"失敗:status_code={rsp.status_code}, message={rsp.message}")
レスポンス例
URL は 24 時間有効です。速やかに画像をダウンロードしてください。
{
"status_code": 200,
"request_id": "81d868c6-6ce1-92d8-a90d-d2ee71xxxxxx",
"code": "",
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
}
]
}
}
],
"audio": null,
"finished": true
},
"usage": {
"input_tokens": 18790,
"output_tokens": 2,
"characters": 0,
"image_count": 1,
"size": "2985*1405",
"total_tokens": 18792
}
}
Java
リクエスト例
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* wan2.7-image-pro 画像編集 - 同期呼び出しの例
*/
public class Main {
static {
// 次の URL はシンガポールリージョン用です。{WorkspaceId} をご利用の Bailian ワークスペース ID に置き換えてください。base_url はリージョンによって異なります。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください:apiKey="sk-xxx"
// API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
// --- Base64 エンコーディング関数 ---
// Base64 エンコーディング形式:data:{MIME_type};base64,{base64_data}
public static String encodeFile(String filePath) throws IOException {
byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
String base64String = Base64.getEncoder().encodeToString(fileContent);
String mimeType = Files.probeContentType(Paths.get(filePath));
return "data:" + mimeType + ";base64," + base64String;
}
public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
/*
* 画像入力方法の説明:
* 以下に 3 つの画像入力方法を示します。いずれか 1 つを選択してください。
* 1. パブリック URL を使用 - 一般公開されている画像に適しています。
* 2. ローカルファイルを使用 - ローカルでの開発やテストに適しています。
* 3. Base64 エンコーディングを使用 - 非公開画像や暗号化伝送が必要なシナリオに適しています。
*/
// 方法 1:パブリック画像 URL を使用します。
String image1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp";
String image2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp";
// 方法 2:ローカルファイルを使用します。絶対パスと相対パスの両方がサポートされています。
// 形式:file:// + ファイルパス
// String image1 = "file:///ご利用のパス/car.png";
// String image2 = "file:///ご利用のパス/paint.png";
// 方法 3:Base64 エンコードされた画像を使用します。
// String image1 = encodeFile("/ご利用のパス/car.png");
// String image2 = encodeFile("/ご利用のパス/paint.png");
// 複数画像の入力メッセージを構築します。
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Arrays.asList(
// 複数画像の入力がサポートされています。複数のリファレンス画像を提供できます。
Collections.singletonMap("text", "画像 2 のグラフィティを画像 1 の車にスプレーする"),
Collections.singletonMap("image", image1),
Collections.singletonMap("image", image2)
)).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.7-image-pro")
.messages(Collections.singletonList(message))
.n(1)
.size("2K") // wan2.7-image-pro の場合、テキストからの画像生成シナリオのみが 4K 解像度をサポートします。画像編集およびコラージュ生成は、最大 2K の解像度をサポートします。
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = null;
try {
System.out.println("---画像編集の同期呼び出し、しばらくお待ちください----");
result = imageGeneration.call(param);
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
// 結果の画像 URL を抽出し、ローカルファイルに保存します。
for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
.getMessage().getContent();
for (int j = 0; j < contents.size(); j++) {
if ("image".equals(contents.get(j).get("type"))) {
String imageUrl = (String) contents.get(j).get("image");
String fileName = "output_" + i + "_" + j + ".png";
// 結果の URL は 24 時間有効です。速やかに画像をダウンロードしてください。
try (InputStream in = new URL(imageUrl).openStream()) {
Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
}
System.out.println("画像が " + fileName + " に保存されました");
}
}
}
}
public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
basicCall();
}
}
レスポンス例
URL は 24 時間有効です。速やかに保存してください。
{
"requestId": "1bf6173a-e8de-9f75-94d3-5e618f875xxx",
"usage": {
"input_tokens": 18790,
"output_tokens": 2,
"total_tokens": 18792,
"image_count": 1,
"size": "2985*1405"
},
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
}
]
}
}
],
"finished": true
},
"status_code": 200,
"code": "",
"message": ""
}
curl
リクエスト例
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
"model": "wan2.7-image-pro",
"input": {
"messages": [
{
"role": "user",
"content": [
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"},
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"},
{"text": "画像 2 のグラフィティを画像 1 の車にスプレーする"}
]
}
]
},
"parameters": {
"size": "2K",
"n": 1,
"watermark": false
}
}'
レスポンス例
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"content": [
{
"image": "https://dashscope-xxx.oss-xxx.aliyuncs.com/xxx.png?Expires=xxx",
"type": "image"
}
],
"role": "assistant"
}
}
],
"finished": true
},
"usage": {
"image_count": 1,
"input_tokens": 10867,
"output_tokens": 2,
"size": "1488*704",
"total_tokens": 10869
},
"request_id": "71dfc3c6-f796-9972-97e4-bc4efc4faxxx"
}
非同期呼び出し
重要DashScope Python SDK のバージョンが1.25.15以降、DashScope Java SDK のバージョンが2.22.13以降であることを確認してください。
Python
リクエスト例
import os
import base64
import mimetypes
import urllib.request
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
from http import HTTPStatus
# 次の base_url はシンガポールリージョン用です。{WorkspaceId} をご利用の Bailian ワークスペース ID に置き換えてください。base_url はリージョンによって異なります。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください:api_key="sk-xxx"
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
api_key = os.getenv("DASHSCOPE_API_KEY")
# --- Base64 エンコーディング関数 ---
# Base64 エンコーディング形式は data:{MIME_type};base64,{base64_data} です
def encode_file(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if not mime_type or not mime_type.startswith("image/"):
raise ValueError("サポートされていない、または認識されない画像形式です。")
with open(file_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
return f"data:{mime_type};base64,{encoded_string}"
"""
画像の入力方法:
以下に 3 つの画像入力方法を示します。いずれか 1 つを選択してください。
1. パブリック URL を使用 - 一般公開されている画像に適しています。
2. ローカルファイルを使用 - ローカルでの開発やテストに適しています。
3. Base64 エンコーディングを使用 - 非公開画像や暗号化伝送が必要なシナリオに適しています。
"""
# [方法 1] パブリック画像 URL を使用
image_1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"
image_2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"
# [方法 2] ローカルファイルを使用 (絶対パスと相対パスをサポート)
# image_1 = "file:///ご利用のパス/car.png"
# image_2 = "file:///ご利用のパス/paint.png"
# [方法 3] Base64 エンコードされた画像を使用
# image_1 = encode_file("/ご利用のパス/car.png")
# image_2 = encode_file("/ご利用のパス/paint.png")
# 非同期タスクを作成します。
def create_async_task():
print("非同期タスクを作成中...")
message = Message(
role="user",
content=[
{"text": "画像 2 のグラフィティを画像 1 の車にスプレーする"},
{"image": image_1},
{"image": image_2},
],
)
response = ImageGeneration.async_call(
model="wan2.7-image-pro",
api_key=api_key,
messages=[message],
watermark=False,
n=1,
size="2K", # wan2.7-image-pro は、テキストからの画像生成シナリオでのみ 4K 解像度をサポートします。画像編集およびコラージュ生成は、最大 2K の解像度をサポートします。
)
if response.status_code == 200:
print("タスクが正常に作成されました:", response)
return response
else:
raise Exception(f"タスクの作成に失敗しました:{response.code} - {response.message}")
# タスクの完了を待ちます。
def wait_for_completion(task_response):
print("タスクの完了を待機中...")
status = ImageGeneration.wait(task=task_response, api_key=api_key)
if status.output.task_status == "SUCCEEDED":
print("タスクが成功しました!")
# 結果の画像 URL を抽出し、画像をローカルファイルに保存します。
for i, choice in enumerate(status.output.choices):
for j, content in enumerate(choice["message"]["content"]):
if content.get("type") == "image":
image_url = content["image"]
file_name = f"output_{i}_{j}.png"
# 結果の URL は 24 時間有効です。速やかに画像をダウンロードしてください。
urllib.request.urlretrieve(image_url, file_name)
print(f"画像が {file_name} に保存されました")
else:
raise Exception(f"タスクはステータス {status.output.task_status} で失敗しました")
# 非同期タスクに関する情報を取得します。
def fetch_task_status(task):
print("タスクステータスを取得中...")
status = ImageGeneration.fetch(task=task, api_key=api_key)
if status.status_code == HTTPStatus.OK:
print("タスクステータス:", status.output.task_status)
print("レスポンス詳細:", status)
else:
print(f"ステータスの取得に失敗しました:{status.code} - {status.message}")
# 非同期タスクをキャンセルします。
def cancel_task(task):
print("タスクをキャンセル中...")
response = ImageGeneration.cancel(task=task, api_key=api_key)
if response.status_code == HTTPStatus.OK:
print("タスクが正常にキャンセルされました:", response.output.task_status)
else:
print(f"タスクのキャンセルに失敗しました:{response.code} - {response.message}")
# メイン実行フロー。
if __name__ == "__main__":
task = create_async_task()
wait_for_completion(task)
レスポンス例
- タスク作成のレスポンス例
{
"status_code": 200,
"request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx",
"code": "",
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": null,
"audio": null,
"task_id": "127ec645-118f-4884-955d-0eba8dxxxxxx",
"task_status": "PENDING"
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"characters": 0
}
}
-
タスク結果のクエリのレスポンス例
URL は 24 時間有効です。速やかに画像をダウンロードしてください。
{
"status_code": 200,
"request_id": "3b99aae5-d26f-9059-8dd0-ee9ca4804xxx",
"code": null,
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
}
]
}
}
],
"audio": null,
"task_id": "127ec645-118f-4884-955d-0eba8dxxxxxx",
"task_status": "SUCCEEDED",
"submit_time": "2026-03-31 22:58:47.646",
"scheduled_time": "2026-03-31 22:58:47.683",
"end_time": "2026-03-31 22:58:59.642",
"finished": true
},
"usage": {
"input_tokens": 18711,
"output_tokens": 2,
"characters": 0,
"size": "2985*1405",
"total_tokens": 18713,
"image_count": 1
}
}
Java
リクエスト例
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* wan2.7-image-pro 画像編集 - 非同期呼び出しの例
*/
public class Main {
static {
// 次の URL はシンガポールリージョン用です。{WorkspaceId} をご利用の Bailian ワークスペース ID に置き換えてください。base_url はリージョンによって異なります。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください:apiKey="sk-xxx"
// API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
// --- Base64 エンコーディング関数 ---
// Base64 エンコーディング形式は data:{MIME_type};base64,{base64_data} です
public static String encodeFile(String filePath) throws IOException {
byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
String base64String = Base64.getEncoder().encodeToString(fileContent);
String mimeType = Files.probeContentType(Paths.get(filePath));
return "data:" + mimeType + ";base64," + base64String;
}
public static void asyncCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
/*
* 画像入力方法の説明:
* 以下に 3 つの画像入力方法を示します。いずれか 1 つを選択してください。
* 1. パブリック URL を使用 - 一般公開されている画像に適しています。
* 2. ローカルファイルを使用 - ローカルでの開発やテストに適しています。
* 3. Base64 エンコーディングを使用 - 非公開画像を含むシナリオや、暗号化伝送が必要なシナリオに適しています。
*/
// [方法 1] パブリック画像 URL を使用
String image1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp";
String image2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp";
// [方法 2] ローカルファイルを使用 (絶対パスと相対パスをサポート)
// 必要な形式:file:// + ファイルパス
// String image1 = "file:///ご利用のパス/car.png";
// String image2 = "file:///ご利用のパス/paint.png";
// [方法 3] Base64 エンコードされた画像を使用
// String image1 = encodeFile("/ご利用のパス/car.png");
// String image2 = encodeFile("/ご利用のパス/paint.png");
// 複数画像の入力メッセージを構築
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Arrays.asList(
// 複数画像の入力がサポートされています。複数のリファレンス画像を提供できます。
Collections.singletonMap("text", "画像 2 のグラフィティを画像 1 の車にスプレーペイントする"),
Collections.singletonMap("image", image1),
Collections.singletonMap("image", image2)
)).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.7-image-pro")
.n(1)
.size("2K") // wan2.7-image-pro モデルは、テキストからの画像生成でのみ 4K 解像度をサポートします。画像編集および合成画像生成では、最大 2K の解像度がサポートされます。
.messages(Arrays.asList(message))
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = null;
try {
System.out.println("---画像編集の非同期呼び出し、タスクを作成中----");
result = imageGeneration.asyncCall(param);
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
System.out.println("タスク作成結果:");
System.out.println(JsonUtils.toJson(result));
String taskId = result.getOutput().getTaskId();
// タスクの完了を待機
waitTask(taskId);
}
public static void waitTask(String taskId) throws ApiException, NoApiKeyException, IOException {
ImageGeneration imageGeneration = new ImageGeneration();
System.out.println("\n---タスクの完了を待機中----");
ImageGenerationResult result = imageGeneration.wait(taskId, apiKey);
// 結果の画像 URL を取得し、ローカルファイルに保存
for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
.getMessage().getContent();
for (int j = 0; j < contents.size(); j++) {
if ("image".equals(contents.get(j).get("type"))) {
String imageUrl = (String) contents.get(j).get("image");
String fileName = "output_" + i + "_" + j + ".png";
// 結果の URL は 24 時間有効です。速やかに画像をダウンロードしてください。
try (InputStream in = new URL(imageUrl).openStream()) {
Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
}
System.out.println("画像が " + fileName + " に保存されました");
}
}
}
}
public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
asyncCall();
}
}
レスポンス例
- タスク作成のレスポンス例
{
"requestId": "ccf4b2f4-bf30-9e13-9461-3a28c6a7bxxx",
"output": {
"task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx",
"task_status": "PENDING"
},
"status_code": 200,
"code": "",
"message": ""
}
-
タスク結果のクエリのレスポンス例
URL は 24 時間有効です。速やかに保存してください。
{
"requestId": "60a08540-f1c1-9e76-8cd3-d5949db8cxxx",
"usage": {
"input_tokens": 18711,
"output_tokens": 2,
"total_tokens": 18713,
"image_count": 1,
"size": "2985*1405"
},
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
}
]
}
}
],
"task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx",
"task_status": "SUCCEEDED",
"finished": true,
"submit_time": "2026-03-31 19:57:58.840",
"scheduled_time": "2026-03-31 19:57:58.877",
"end_time": "2026-03-31 19:58:11.563"
},
"status_code": 200,
"code": "",
"message": ""
}
curl
ステップ 1:タスクを作成してタスク ID を取得
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "X-DashScope-Async: enable" \
--data '{
"model": "wan2.7-image-pro",
"input": {
"messages": [
{
"role": "user",
"content": [
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"},
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"},
{"text": "画像 2 のグラフィティを画像 1 の車にスプレーする"}
]
}
]
},
"parameters": {
"size": "2K",
"n": 1,
"watermark": false
}
}'
レスポンス例{
"output": {
"task_status": "PENDING",
"task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
},
"request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}
ステップ2:タスク ID で結果をクエリ
前のステップで取得した task_id を使用して、task_status が SUCCEEDED または FAILED になるまで API を介してタスクのステータスをポーリングします。
{task_id} を、前の API 呼び出しで返された task_id の値に置き換えます。task_id は 24 時間クエリに有効です。{WorkspaceId} を実際の ワークスペース ID に置き換えてください。
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
レスポンス例画像 URL は 24 時間有効です。速やかに画像をダウンロードしてください。
{
"request_id": "810fa5f5-334c-91f3-aaa4-ed89cf0caxxx",
"output": {
"task_id": "a81ee7cb-014c-473d-b842-76e98311cxxx",
"task_status": "SUCCEEDED",
"submit_time": "2026-03-26 17:16:01.663",
"scheduled_time": "2026-03-26 17:16:01.716",
"end_time": "2026-03-26 17:16:22.961",
"finished": true,
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-xxx.oss-xxx.aliyuncs.com/xxx.png?Expires=xxx",
"type": "image"
}
]
}
}
]
},
"usage": {
"size": "2976*1408",
"total_tokens": 11017,
"image_count": 1,
"output_tokens": 2,
"input_tokens": 11015
}
}
wan2.5-i2i-preview は、異なる API エンドポイントとパラメーターを使用します。
wan2.5-i2i-preview の呼び出し例を表示するにはクリック
同期呼び出し
重要
DashScope Python SDK のバージョンが1.25.2 以降、DashScope Java SDK のバージョンが 2.22.2 以降であることを確認してください。古いバージョンの SDK を使用すると、「url error, please check url!」というエラーが発生する可能性があります。SDK のインストールまたはアップグレードを行ってください。
Python
この例では、公開 URL、Base64 エンコーディング、ローカルファイルパスの 3 つの画像入力メソッドをサポートしています。
リクエストの例
import base64
import mimetypes
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import dashscope
import requests
from dashscope import ImageSynthesis
import os
# 以下の URL はシンガポールリージョン用です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# 環境変数を設定していない場合は、次の行を api_key="sk-xxx" に置き換えてください。
# API キーはシンガポールと北京で異なります。API キーの取得方法:https://www.alibabacloud.com/help/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# --- 入力画像:Base64 エンコーディング ---
# Base64 フォーマット:data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if not mime_type or not mime_type.startswith("image/"):
raise ValueError("Unsupported or unrecognized image format")
with open(file_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
return f"data:{mime_type};base64,{encoded_string}"
"""
画像入力メソッド:
次のいずれかを選択してください:
1. 公開 URL — 公開されている画像に最適
2. ローカルファイル — ローカルでの開発およびテストに最適
3. Base64 エンコーディング — 非公開画像や安全な送信に最適
"""
# [メソッド 1] 公開画像の URL
image_url_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp"
image_url_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
# [メソッド 2] ローカルファイル (絶対パスと相対パスをサポート)
# フォーマット:file:// + ファイルパス
# 例 (絶対パス):
# image_url_1 = "file://" + "/path/to/your/image_1.png" # Linux/macOS
# image_url_2 = "file://" + "C:/path/to/your/image_2.png" # Windows
# 例 (相対パス):
# image_url_1 = "file://" + "./image_1.png" # ご利用のパスに合わせて調整してください
# image_url_2 = "file://" + "./image_2.png" # ご利用のパスに合わせて調整してください
# [メソッド 3] Base64 エンコードされた画像
# image_url_1 = encode_file("./image_1.png") # ご利用のパスに合わせて調整してください
# image_url_2 = encode_file("./image_2.png") # ご利用のパスに合わせて調整してください
print('----sync call, please wait a moment----')
rsp = ImageSynthesis.call(api_key=api_key,
model="wan2.5-i2i-preview",
prompt="Place the alarm clock from image 1 beside the vase on the dining table in image 2.",
images=[image_url_1, image_url_2],
negative_prompt="",
n=1,
# size="1280*1280",
prompt_extend=True,
watermark=False,
seed=12345)
print('response: %s' % rsp)
if rsp.status_code == HTTPStatus.OK:
# 画像を現在のディレクトリに保存
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(result.url).content)
else:
print('sync_call Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
レスポンスの例
イメージ URL は 24 時間有効です。速やかにイメージをダウンロードしてください。
{
"status_code": 200,
"request_id": "8ad45834-4321-44ed-adf5-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "3aff9ebd-35fc-4339-98a3-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
"orig_prompt": "Place the alarm clock from image 1 beside the vase on the dining table in image 2.",
"actual_prompt": "Place the blue alarm clock from image 1 to the right of the vase on the dining table in image 2, near the edge of the tablecloth. Keep the clock facing the camera and parallel to the tabletop, with natural shadow projection."
}
],
"submit_time": "2025-10-23 16:18:16.009",
"scheduled_time": "2025-10-23 16:18:16.040",
"end_time": "2025-10-23 16:19:09.591",
"task_metrics": {
"TOTAL": 1,
"FAILED": 0,
"SUCCEEDED": 1
}
},
"usage": {
"image_count": 1
}
}
Java
この例では、3つの画像入力メソッドをサポートしています:公開 URL、Base64 エンコーディング、ローカルファイルパス。
リクエストの例
// Copyright (c) Alibaba, Inc. and its affiliates.
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class Image2Image {
static {
// 以下の URL はシンガポールリージョン用です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// 環境変数を設定していない場合は、次の行を apiKey="sk-xxx" に置き換えてください。
// API キーはシンガポールと北京で異なります。API キーの取得方法:https://www.alibabacloud.com/help/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
/**
* 画像入力メソッド:いずれかを選択
*
* 1. 公開 URL — 公開されている画像に最適
* 2. ローカルファイル — ローカルでの開発およびテストに最適
* 3. Base64 エンコーディング — 非公開画像や安全な送信に最適
*/
// [メソッド 1] 公開 URL
static String imageUrl_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp";
static String imageUrl_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp";
// [メソッド 2] ローカルファイルパス (file://+絶対パス または file:///+絶対パス)
// static String imageUrl_1 = "file://" + "/your/path/to/image_1.png"; // Linux/macOS
// static String imageUrl_2 = "file:///" + "C:/your/path/to/image_2.png"; // Windows
// [メソッド 3] Base64 エンコーディング
// static String imageUrl_1 = encodeFile("/your/path/to/image_1.png");
// static String imageUrl_2 = encodeFile("/your/path/to/image_2.png");
// 編集する画像のリスト
static List<String> imageUrls = new ArrayList<>();
static {
imageUrls.add(imageUrl_1);
imageUrls.add(imageUrl_2);
}
public static void syncCall() {
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.5-i2i-preview")
.prompt("Place the alarm clock from image 1 beside the vase on the dining table in image 2.")
.images(imageUrls)
.n(1)
//.size("1280*1280")
.negativePrompt("")
.promptExtend(true)
.watermark(false)
.seed(12345)
.build();
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
System.out.println("---sync call, please wait a moment----");
result = imageSynthesis.call(param);
} catch (ApiException | NoApiKeyException e){
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
}
/**
* ファイルを Base64 文字列としてエンコードする
* @param filePath ファイルパス
* @return Base64 文字列 (フォーマット:data:{MIME_type};base64,{base64_data})
*/
public static String encodeFile(String filePath) {
Path path = Paths.get(filePath);
if (!Files.exists(path)) {
throw new IllegalArgumentException("File not found: " + filePath);
}
// MIME タイプを検出
String mimeType = null;
try {
mimeType = Files.probeContentType(path);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot detect file type: " + filePath);
}
if (mimeType == null || !mimeType.startsWith("image/")) {
throw new IllegalArgumentException("Unsupported or unrecognized image format");
}
// ファイルを読み込んでエンコード
byte[] fileBytes = null;
try{
fileBytes = Files.readAllBytes(path);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot read file: " + filePath);
}
String encodedString = Base64.getEncoder().encodeToString(fileBytes);
return "data:" + mimeType + ";base64," + encodedString;
}
public static void main(String[] args) {
syncCall();
}
}
レスポンスの例
イメージ URL は 24 時間有効です。速やかにイメージをダウンロードしてください。
{
"request_id": "d362685b-757f-4eac-bab5-xxxxxx",
"output": {
"task_id": "bfa7fc39-3d87-4fa7-b1e6-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"orig_prompt": "Place the alarm clock from image 1 beside the vase on the dining table in image 2.",
"actual_prompt": "Place the blue alarm clock from image 1 to the right of the vase on the dining table in image 2, near the edge of the tablecloth. Keep the clock facing the camera and parallel to the vase.",
"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"
}
],
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
}
},
"usage": {
"image_count": 1
}
}
非同期呼び出し
重要
DashScope Python SDK のバージョンが1.25.2 以降、DashScope Java SDK のバージョンが 2.22.2 以降であることを確認してください。古いバージョンの SDK を使用すると、「url error, please check url!」というエラーが発生する可能性があります。SDK のインストールまたはアップグレードを行ってください。
Python
この例では、公開 URL を使用して画像を渡します。
リクエストの例
import os
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import dashscope
import requests
from dashscope import ImageSynthesis
# 以下の URL はシンガポールリージョン用です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# 環境変数を設定していない場合は、次の行を api_key="sk-xxx" に置き換えてください。
# API キーはシンガポールと北京で異なります。API キーの取得方法:https://www.alibabacloud.com/help/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# 公開画像の URL
image_url_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp"
image_url_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
def async_call():
print('----create task----')
task_info = create_async_task()
print('----wait task----')
wait_async_task(task_info)
# 非同期タスクの作成
def create_async_task():
rsp = ImageSynthesis.async_call(api_key=api_key,
model="wan2.5-i2i-preview",
prompt="Place the alarm clock from image 1 beside the vase on the dining table in image 2.",
images=[image_url_1, image_url_2],
negative_prompt="",
n=1,
# size="1280*1280",
prompt_extend=True,
watermark=False,
seed=12345)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
return rsp
# 非同期タスクの完了を待機
def wait_async_task(task):
rsp = ImageSynthesis.wait(task=task, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
# ファイルを現在のディレクトリに保存
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(result.url).content)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
# 非同期タスクのステータスを取得
def fetch_task_status(task):
status = ImageSynthesis.fetch(task=task, api_key=api_key)
print(status)
if status.status_code == HTTPStatus.OK:
print(status.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(status.status_code, status.code, status.message))
# 非同期タスクをキャンセル。PENDING 状態のタスクのみキャンセル可能。
def cancel_task(task):
rsp = ImageSynthesis.cancel(task=task, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
async_call()
レスポンスの例
- タスク作成時のレスポンス
{
"status_code": 200,
"request_id": "31b04171-011c-96bd-ac00-f0383b669cc7",
"code": "",
"message": "",
"output": {
"task_id": "4f90cf14-a34e-4eae-xxxxxxxx",
"task_status": "PENDING",
"results": []
},
"usage": null
}
- タスク結果のクエリ時のレスポンス
イメージ URL は 24 時間後に有効期限切れになります。速やかにイメージをダウンロードしてください。
{
"status_code": 200,
"request_id": "8ad45834-4321-44ed-adf5-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "3aff9ebd-35fc-4339-98a3-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
"orig_prompt": "Place the alarm clock from image 1 beside the vase on the dining table in image 2.",
"actual_prompt": "Place the blue alarm clock from image 1 to the right of the vase on the dining table in image 2, near the edge of the tablecloth. Keep the clock facing the camera and parallel to the tabletop, with natural shadow projection."
}
],
"submit_time": "2025-10-23 16:18:16.009",
"scheduled_time": "2025-10-23 16:18:16.040",
"end_time": "2025-10-23 16:19:09.591",
"task_metrics": {
"TOTAL": 1,
"FAILED": 0,
"SUCCEEDED": 1
}
},
"usage": {
"image_count": 1
}
}
Java
この例では、デフォルトで公開 URL を使用して画像を渡します。
リクエストの例
// Copyright (c) Alibaba, Inc. and its affiliates.
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisListResult;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.ArrayList;
import java.util.List;
public class Image2Image {
static {
// 以下の URL はシンガポールリージョン用です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// 環境変数を設定していない場合は、次の行を apiKey="sk-xxx" に置き換えてください。
// API キーはシンガポールと北京で異なります。API キーの取得方法:https://www.alibabacloud.com/help/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
// 公開 URL
static String imageUrl_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp";
static String imageUrl_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp";
// 編集する画像のリスト
static List<String> imageUrls = new ArrayList<>();
static {
imageUrls.add(imageUrl_1);
imageUrls.add(imageUrl_2);
}
public static void asyncCall() {
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.5-i2i-preview")
.prompt("Place the alarm clock from image 1 beside the vase on the dining table in image 2.")
.images(imageUrls)
.n(1)
//.size("1280*1280")
.negativePrompt("")
.promptExtend(true)
.watermark(false)
.seed(12345)
.build();
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
System.out.println("---async call, please wait a moment----");
result = imageSynthesis.asyncCall(param);
} catch (ApiException | NoApiKeyException e){
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
String taskId = result.getOutput().getTaskId();
System.out.println("taskId=" + taskId);
try {
result = imageSynthesis.wait(taskId, apiKey);
} catch (ApiException | NoApiKeyException e){
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
System.out.println(JsonUtils.toJson(result.getOutput()));
}
public static void listTask() throws ApiException, NoApiKeyException {
ImageSynthesis is = new ImageSynthesis();
AsyncTaskListParam param = AsyncTaskListParam.builder().build();
param.setApiKey(apiKey);
ImageSynthesisListResult result = is.list(param);
System.out.println(result);
}
public void fetchTask(String taskId) throws ApiException, NoApiKeyException {
ImageSynthesis is = new ImageSynthesis();
// DASHSCOPE_API_KEY が環境変数として設定されている場合、apiKey は空にできます。
ImageSynthesisResult result = is.fetch(taskId, apiKey);
System.out.println(result.getOutput());
System.out.println(result.getUsage());
}
public static void main(String[] args) {
asyncCall();
}
}
レスポンスの例
- タスク作成時のレスポンス
{
"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
"output": {
"task_id": "7277e20e-aa01-4709-xxxxxxxx",
"task_status": "PENDING"
}
}
- タスク結果のクエリ時のレスポンス
イメージ URL は 24 時間後に有効期限切れになります。速やかにイメージをダウンロードしてください。
{
"request_id": "d362685b-757f-4eac-bab5-xxxxxx",
"output": {
"task_id": "bfa7fc39-3d87-4fa7-b1e6-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"orig_prompt": "Place the alarm clock from image 1 beside the vase on the dining table in image 2.",
"actual_prompt": "Place the blue alarm clock from image 1 to the right of the vase on the dining table in image 2, near the edge of the tablecloth. Keep the clock facing the camera and parallel to the vase.",
"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"
}
],
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
}
},
"usage": {
"image_count": 1
}
}
curl
これは 2 段階のプロセスです:タスクを作成し、その後結果を取得します。
注記
- 非同期呼び出しの場合、ヘッダーパラメーター
X-DashScope-Asyncをenableに設定します。 - 非同期タスクの
task_idは 24 時間有効です。有効期限が切れると、タスクのステータスはUNKNOWNになります。
ステップ1:タスク作成リクエストの送信
このリクエストはタスク ID (task_id) を返します。
リクエストの例
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
-H 'X-DashScope-Async: enable' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "wan2.5-i2i-preview",
"input": {
"prompt": "Place the alarm clock from image 1 beside the vase on the dining table in image 2.",
"images": [
"https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp",
"https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
]
},
"parameters": {
"n": 1
}
}'
レスポンスの例{
"output": {
"task_status": "PENDING",
"task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
},
"request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}
ステップ2:タスク ID による結果のクエリ
前のステップで取得した task_id を使用して、API を通じてタスクステータスをポーリングし、task_status が SUCCEEDED または FAILED になるまで続けます。
{task_id} を、前の API 呼び出しで返された task_id の値に置き換えます。task_id は 24 時間クエリに対して有効です。{WorkspaceId} を実際の ワークスペース ID に置き換えてください。
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
レスポンスの例イメージ URL は 24 時間有効です。速やかにイメージをダウンロードしてください。
{
"request_id": "d1f2a1be-9c58-48af-b43f-xxxxxx",
"output": {
"task_id": "7f4836cd-1c47-41b3-b3a4-xxxxxx",
"task_status": "SUCCEEDED",
"submit_time": "2025-09-23 22:14:10.800",
"scheduled_time": "2025-09-23 22:14:10.825",
"end_time": "2025-09-23 22:15:23.456",
"results": [
{
"orig_prompt": "Place the alarm clock from image 1 next to the vase on the dining table in image 2",
"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"
}
],
"task_metrics": {
"TOTAL": 1,
"FAILED": 0,
"SUCCEEDED": 1
}
},
"usage": {
"image_count": 1
}
}
モデルの選択
-
wan2.7-image-pro および wan2.7-image (推奨):精密な編集や一貫性のある複数のイメージの生成に最適です。
- 精密な局所編集:特定のエリアを選択して、要素を移動、置き換え、または追加します。E コマースのレタッチやデザイン調整に最適です。
- マルチパネル生成:1 回の呼び出しで、一貫したスタイルの複数のイメージを生成します。漫画のストーリーボードやプロダクトシリーズに最適です。
-
wan2.6-image:テキストとイメージの混合、または複数のリファレンスを用いた様式化編集に適しています。イメージ内にテキストを生成でき、最大 4 つのリファレンスイメージに対応します。
-
wan2.5-i2i-preview:シンプルな画像編集や複数イメージの融合に適しています。
各モデルの入出力仕様については、入力イメージの仕様および出力イメージの解像度をご参照ください。
デモギャラリー
画像から画像への変換セット
入力画像 | 出力画像 |
|---|---|
|
|
|
|
プロンプトを表示するにはクリック
ケース 1:写真撮影
キャラクターの基本設定:20歳の東アジア人男性。ミディアム丈のカーリーヘア、芸術的な雰囲気、はっきりとした顔立ち、繊細な目元。シンプルな白の Tシャツまたは水色のシャツを着用し、若々しく自然な雰囲気を醸し出している。
1. 民国時代の学者風
プロンプト:
[顔の基本描写] キャラクターの外見は参考画像 1 に基づき、濃いシアン色の長袍と丸い金縁メガネをかけ、扇子を持っている。背景は古い上海の書斎で、木製の本棚、温かみのある黄色の色調、レトロなフィルムの質感、柔らかいサイドライト、光線の中で舞う埃が、文化的で静かな雰囲気を醸し出している。ハッセルブラッド中判、85mm レンズ、高解像度、映画的なカラーグレーディング、ウォン・カーウァイ風。
小道具:扇子 / 和綴じ本 / 丸メガネ
色調:温かい黄色 / ダークシアン / セピア
2. 英国紳士風
プロンプト:
[顔の基本描写] キャラクターの外見は参考画像 1 に基づき、ダークグレーのツイード製スリーピーススーツとヴィンテージの機械式腕時計を身に着け、赤ワインのグラスを持って見つめている。背景はクラシックな図書館またはプライベートクラブで、ダークレザーのソファ、レンブラントライティングが、暗くエレガントで高貴な雰囲気を醸し出している。クールな眼差し、豊かなディテールとクリアな質感で、英国貴族の気品を漂わせる。8K 解像度、ファッション雑誌風ショット。
小道具:ワイングラス / パイプ / 機械式腕時計
色調:ダークグレー / バーガンディ / ダークゴールド
3. 90年代香港レトロ風
プロンプト:
[顔の基本描写] キャラクターの外見は参考画像 1 に基づき、ウォッシュドデニムジャケットまたは花柄シャツを着用し、少し乱れた髪で腕を組んでいる。背景は夜のネオンサインが輝く通りで、ぼやけた光点、高い粒子感、豊かな色彩が特徴で、赤と青の色の対比が見られる。ウォン・カーウァイ風、エモーショナル、夢見るような眼差し、直接的なフラッシュ効果、ノスタルジックな雰囲気。[全身ショット]。
色調:ネオンレッド / ダークブルー / フィルムグリーン
4. 新中式禅意風
プロンプト:
[顔の基本描写] キャラクターの外見は参考画像 1 に基づき、歯を見せてわずかに微笑み、アレンジされた白いチャイナカラーのシャツを着用し、梅の枝を持っている。背景はミニマルな白壁または竹林で、太陽光が壁にまだらな影を落としている。色調はクールで静謐、東洋の美学を体現している。肌は半透明で、高い粒子感とマットな仕上がり。構図はシンプルで、光と影の層が豊か。ハイエンドな写真、禅の雰囲気。
小道具:梅の枝
色調:白 / ダークグリーン / ライトグレー
5. ヴィンテージアーティスト風
プロンプト:
[顔の基本描写] キャラクターの外見は参考画像 1 に基づき、絵の具で汚れた白いシャツと茶色の革製エプロンを着用し、絵筆またはパレットを持っている。背景は明るい光とカラフルな光と影のある清潔なアトリエ。集中した表情で、カメラではなく手の中の絵の具を見ている。髪は少し乱れ、芸術的なセンス、印象派の色調、強い質感が特徴。
小道具:絵筆 / パレット / スケッチブック
色調:温かい光 / カラフルな絵の具 / ブラウン
6. クラシックノワール白黒風
プロンプト:
[顔の基本描写] キャラクターの外見は参考画像 1 に基づき、黒のタートルネックセーターを着用し、タバコを持ち、黒の中折れ帽をかぶっている。背景は影が交差する階段または廊下。ハイコントラストの白黒写真、硬い照明、強い影、ミステリアスな雰囲気、ハードボイルド探偵風。顔の輪郭はシャープで、肌の質感は非常にクリア。クラシックな映画のスチール写真、時代を超えた感覚、横顔のクローズアップ、芸術的な写真。
小道具:杖 / 中折れ帽 / サングラス
色調:白黒 / ハイコントラスト
ケース 2:ビジュアルデザイン
画像 1:商業レベルのプロダクト撮影によるメインビジュアルカバー画像、正面からのパノラマ構図。レトロフューチャーなワイヤレスオーバーイヤーヘッドホンが幾何学的な石膏のフォルムの上に浮かび、完璧な対称美を見せている。素材はシャンパンゴールドの金属とクリームホワイトのシェル。背景は深くぼかされた温かい室内の光と影で、柔らかな光がプロダクトのシルエットを縁取っている。画像内の余白が強い抜け感を生み出し、静かな聴覚体験を暗示している。8K 超高解像度、ミニマルで高級感のある仕上がり。
画像 2:プロダクトの素材ディテールを捉えた 100mm マクロ撮影。ヘッドホンの伸縮アームの接続部にクローズアップ。シャンパンゴールドのヘアライン加工されたアルミニウム合金の質感と、CNC 精密カットによる面取りがはっきりと見える。シャープな逆光が金属のエッジにスターバースト状のハイライトを生み出している。背景は暗くして、金属の工業的な精密さを強調。画質は極めてシャープでノイズなし。
画像 3:素材の極端なクローズアップマクロ撮影。モカ色のプロテインレザー製イヤーカップの表面にフォーカス。サイドからの照明が、レザーの微細な毛穴の質感、押したときの柔らかいしわ、通気孔のディテールを明らかにし、究極の肌触りの良さと弾力性を伝えている。光と影の層が豊かで、色調は温かくしっとりしている。超高精細マクロ撮影。
画像 4:プロダクトの芸術的な分解図。レトロフューチャーなヘッドホンの内部サウンドユニット、ノイズキャンセリングチップ、バッテリーモジュール、外部のウォールナット材装飾パネル、金属フレームが、浮遊・分解された状態で表示されている。背景は深いテックブルーで、内部コンポーネントは半透明のホログラフィックな技術的質感を持ち、内部の精密な職人技と現代技術の融合を強調している。ハイテクな商業ポスタースタイル。
画像 5:装着シーンを捉えた 35mm のヒューマニスティックなショット。モデルの顎のラインと首にクローズアップし、シャンパンゴールドのヘッドホンが完璧にフィットしている様子を見せる。斜め後ろからの自然で温かい夕日がリムライトを作り出し、髪の端が金色に輝いている。モデルの肌の色は健康的で自然な質感で、リラックスして音楽に没頭するライフスタイル感を演出。背景はぼやけた自宅の環境。
画像 6:建築的な光と影に敬意を表した静物写真。ヘッドホンはミニマルなグレーのコンクリートテーブルの上に置かれている。午後の日差しがブラインドを通して差し込み、マットなクリームホワイトのボディとシャンパンゴールドのフレームに縞模様の硬い影を落とし、光と闇の強い幾何学的な構図を作り出している。これにより、ボディの立体的な形状と素材の対比が際立っている。寒色と暖色の対比、ミニマルな構図。
画像 7:カラーオプションを示すトップダウンの平置き構図。シリーズの 3 つのヘッドホンが、シルバーホワイト、ブラックゴールド、ブルーカッパーという異なる配色で並べられている。背景は質感の高いグレーのウールフェルト生地。柔らかなトップライトが CMF デザインの多様性と素材の繊細な手触りを強調している。画像はクリーンで整然としており、デザイン雑誌のようなスタイル。
画像 8:ブランドのライフスタイルを表現したファミリーポートレート風の静物写真。レトロフューチャーなヘッドホンが、それに合う精巧なレザーケースの隣に置かれている。テーブルの上にはレコードプレーヤー、回転するレコード、そして湯気の立つコーヒーカップがある。背景は温かいアンビエント照明でレンダリングされ、深いウォールナットの木の色調が支配的で、ゆったりとしたライフスタイルと高品位な音質を両立させるというブランド哲学を伝えている。映画のような物語性のあるライティング。
インタラクティブ編集
入力画像 | 出力画像 |
|---|---|
|
画像 1 を基に編集します。ボックス 1 で選択されたラズベリーをレモンに、ボックス 2 のラズベリーをイチゴに、ボックス 3 のラズベリーをブルーベリーに置き換えます。結果は元の画像と自然に融合させ、参照用のボックスと番号は表示せず、他の部分は変更しません。 |
|
画像 1 で選択したパターンを、画像 2 で選択した領域に配置します。 |
複数画像の融合
入力画像 | 出力画像 |
|---|---|
|
画像 1 の男の子と画像 2 の犬のポートレートを撮影します。男の子は犬を抱きしめており、二人ともとても幸せそうです。スタジオのソフトな照明、青いテクスチャの背景。 |
|
画像 2 の鳥の色を使い、画像 1 のドレスを再配色します。ドレスのスタイルとモデルは変更せず、芸術的に仕上げます。 |
被写体の特徴維持
入力画像 | 出力画像 |
|---|---|
|
「季節の移り変わり」をテーマにしたポラロイド写真 4 枚セットを生成してください。各写真は公園の木の下の同じ場所で撮影されていますが、それぞれ春、夏、秋、冬の風景が写っています。人物の服装も季節に合わせて、春は薄手のジャケット、夏は半袖シャツ、秋はトレンチコート、冬はマフラーと厚手のコートを着用しています。この写真セットをダイニングテーブルの上に配置してください。 |
検出とセグメンテーション
入力画像 | 出力画像 |
|---|---|
|
画像内のノートパソコンと目覚まし時計を検出し、バウンディングボックスを描画して、「laptop」と「clock」というラベルを付けます。 |
|
画像内のガラスカップをセグメント化します。 |
要素の抽出
入力画像 | 出力画像 |
|---|---|
|
アップロードされた写真から衣類アイテムを抽出し、真っ白な背景に平置きで配置します。リアルなディテールと素材の質感を維持します。ファッション EC サイト風で、衣類ディスプレイに適しています。 |
テキスト編集
入力画像 | 出力画像 |
|---|---|
|
画像からすべてのウォーターマークを削除します。 |
|
砂浜に手で「Time for Holiday?」とさりげなく書きます。 |
|
18 を 29 に、JUNE を SEPTEMBER に変更します。 |
カメラと視点の編集
入力画像 | 出力画像 |
|---|---|
|
人物の特徴は変更せずに、正面、側面、背面のビューを生成します。 |
|
この写真を魚眼レンズで再撮影します。 |
入力仕様
入力イメージの仕様
仕様 | wan2.7-image-pro、wan2.7-image | wan2.6-image | wan2.5-i2i-preview |
|---|---|---|---|
入力イメージ数 | 0~9 (0 は Text-to-Image モードに対応) | イメージ編集:1~4 / テキストとイメージの混在:0~1 | 1~3 |
イメージフォーマット | JPEG、JPG、PNG (alpha チャンネルは非対応)、BMP、WEBP | JPEG、JPG、PNG (alpha チャンネルは非対応)、BMP、WEBP | JPEG、JPG、PNG (alpha チャンネルは非対応)、BMP、WEBP |
イメージの幅と高さの範囲 | [240, 8000] ピクセル | [240, 8000] ピクセル | [384, 5000] ピクセル |
ファイルサイズ | 20 MB 以下 | 10 MB 以下 | 10 MB 以下 |
アスペクト比 | [1:8, 8:1] | 無制限 | [1:4, 4:1] |
イメージの入力順序
プロンプト内のイメージ番号は配列の位置に対応します。最初のイメージは「image 1」、2 番目のイメージは「image 2」です。「[image 1]」や「[image 2]」のようなマーカーも使用できます。
{
"content": [
{"text": "編集命令の例:image 1 の目覚まし時計を image 2 のダイニングテーブルにある花瓶の隣に置く"},
{"image": "https://example.com/image1.png"},
{"image": "https://example.com/image2.png"}
]
}
入力イメージ | 出力イメージ | ||
|---|---|---|---|
イメージ 1 |
イメージ 2 |
プロンプト:イメージ 1 をイメージ 2 の上に移動 |
プロンプト:イメージ 2 をイメージ 1 の上に移動 |
イメージの入力方法
以下のいずれかの方法でイメージを渡します:
方法 2:Base64 エンコーディング
イメージファイルを Base64 エンコードされた文字列に変換し、data:{MIME_type};base64,{base64_data} の形式でフォーマットします。
-
値の例:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDg......(長さの制限により、これはスニペットです)。呼び出しを行う際は、完全な文字列を渡してください。 -
{base64_data}:イメージファイルの Base64 エンコードされた文字列。
-
{MIME_type}:イメージのメディアタイプ。ファイル形式と一致している必要があります。
イメージフォーマット
MIME タイプ
JPEG
image/jpeg
JPG
image/jpeg
PNG
image/png
BMP
image/bmp
WEBP
image/webp
-
ローカル、非公開、または暗号化されたイメージの送信に使用します。
方法 3:ローカルファイルパス (SDK のみ)
-
Python SDK:絶対パスと相対パスの両方をサポートしています。ファイルパスのルールは以下の通りです:
システム
入力ファイルパス
例 (絶対パス)
例 (相対パス)
Linux または macOS
file://{ファイルの絶対パスまたは相対パス}
file:///home/images/test.png
file://./images/test.png
Windows
file://D:/images/test.png
file://./images/test.png
-
Java SDK:絶対パスのみをサポートしています。ファイルパスのルールは以下の通りです:
システム
入力ファイルパス
例 (絶対パス)
Linux または macOS
file://{ファイルの絶対パス}
file:///home/images/test.png
Windows
file:///{ファイルの絶対パス}
file:///D:/images/test.png
-
ローカル開発での迅速なテストに使用します。
主な特徴
1. 命令追従 (プロンプト)
パラメーター:messages.content.text または input.prompt (必須)、negative_prompt (オプション)。
- text または prompt (ポジティブプロンプト):出力画像のコンテンツ、主題、シーン、スタイル、ライティング、構図を記述します。
- negative_prompt (ネガティブプロンプト):「ぼやけ」や「指が多い」など、不要なコンテンツを指定します。
パラメーター | wan2.7-image-pro、wan2.7-image | wan2.6-image | wan2.5-i2i-preview |
|---|---|---|---|
text | 必須、最大 5,000 文字 | 必須、最大 2,000 文字 | サポートされていません |
prompt | サポートされていません | サポートされていません | 必須、最大 2,000 文字 |
negative_prompt | サポートされていません | サポートされています、最大 500 文字 | サポートされています、最大 500 文字 |
2. インテリジェントなプロンプトリライトの有効化
パラメーター:parameters.prompt_extend (bool、デフォルトは true)。
短いプロンプトを拡張して画質を向上させますが、応答時間が増加します。
ベストプラクティス:
- 有効化:プロンプトが簡潔または広範な場合。
- 無効化:細かいディテールの制御、詳細な説明、または遅延の影響を受けやすいシナリオの場合。
prompt_extendをfalseに設定します。
パラメーター | wan2.7-image-pro、wan2.7-image | wan2.6-image | wan2.5-i2i-preview |
|---|---|---|---|
prompt_extend | サポートされていません | サポートされています (画像編集モードのみ) | サポートされています |
3. 出力画像の解像度設定
パラメーター:parameters.size (string)、フォーマットは "幅*高さ" です。
| パラメーター | wan2.7-image-pro、wan2.7-image | wan2.6-image | wan2.5-i2i-preview |
|---|---|---|---|
size | 方法 1:出力画像の解像度を指定 (推奨) 編集モード (少なくとも 1 つの画像が渡された場合) では、オプションの出力解像度レベルは
| 方法 1:入力画像のアスペクト比を参照 (推奨) 編集モード (
| 生成する画像の幅と高さのピクセル値の指定のみをサポート
|
4. インタラクティブな精密編集
parameters.bbox_list を使用して、編集する特定の領域を選択します。wan2.7-image-pro および wan2.7-image のみでサポートされています。
- リストの長さ:入力画像の数と一致させる必要があります。編集が不要な画像には、空のリスト
[]を使用します。 - 座標フォーマット:
[x1, y1, x2, y2](左上の x、左上の y、右下の x、右下の y)。座標は、原点 (0, 0) が左上、X 軸が右向き、Y 軸が下向きの絶対ピクセル値です。 - 数量制限:画像ごとに最大 2 つのバウンディングボックス。
例:3 つの入力画像があり、画像 1 には 2 つのバウンディングボックスがあり、画像 2 にはバウンディングボックスがない場合
[
[[0, 0, 12, 12], [25, 25, 100, 100]], # 画像 1 (2 つのボックス)
[], # 画像 2 (ボックスなし)
[[10, 10, 50, 50]] # 画像 3 (1 つのボックス)
]
クリックして呼び出し例を表示
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
"model": "wan2.7-image-pro",
"input": {
"messages": [
{
"role": "user",
"content": [
{"image": "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp"},
{"image": "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"},
{"text": "画像 1 の目覚まし時計を画像 2 のバウンディングボックスに配置し、シーンとライティングが自然に溶け込むようにしてください。"}
]
}
]
},
"parameters": {
"bbox_list": [[],[[989, 515, 1138, 681]]],
"size": "2K",
"n": 1,
"watermark": false
}
}'
編集領域の座標を決定する方法
画像上でマウスをドラッグしてバウンディングボックスを描画することで、正確かつ直感的な選択が可能です:
# 依存関係のインストール:pip install opencv-python
import cv2
import urllib.request
# サンプル画像をダウンロード (ご利用の画像 URL またはローカルパスに置き換えてください)
image_url = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
urllib.request.urlretrieve(image_url, "example.webp")
# 画像を読み込み、インタラクティブウィンドウを開く
img = cv2.imread("example.webp")
# ポップアップウィンドウでマウスをドラッグしてボックスを描画します。Enter キーで確定、Esc キーでキャンセルします
x, y, w, h = cv2.selectROI("Draw bounding box (Enter=confirm, Esc=cancel)", img)
cv2.destroyAllWindows()
# OpenCV から返された (x, y, w, h) を bbox_list で必要な [x1, y1, x2, y2] フォーマットに変換する
# 座標系:原点は左上隅、X 軸は右向き、Y 軸は下向き、単位はピクセル
bbox = [x, y, x + w, y + h]
print(f"Bounding box coordinates: {bbox}") # これらの座標を parameters.bbox_list に渡します
方法 2:視覚理解モデルqwen3.6-plus を使用して、自然言語でターゲットを記述することにより、ターゲット領域の座標を自動的に特定します:
# 依存関係のインストール:pip install dashscope pillow
import os
import json
from dashscope import MultiModalConversation
import dashscope
from PIL import Image
import urllib.request
# 次の URL はシンガポールリージョン用です。WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
def get_bbox_list(image, prompt):
"""
qwen3.6-plus を使用して画像内のターゲット領域を特定し、絶対ピクセル座標を返します。
Args:
image:画像 URL またはローカルパス (ローカルパスのフォーマット:「file:///absolute/path.png」)
prompt:自然言語による説明 (例:「コーヒーカップ」、「皿の上のすべての果物」、「皿の中央にある果物」)
Returns:
[[x1, y1, x2, y2], ...] bbox_list に直接渡すことができる絶対ピクセル座標
"""
# ユーザーの説明と返却フォーマットの指示を連結する
full_prompt = (
prompt + "\n"
"上記の説明に基づいて、対応する領域の座標を返します。\n"
"最大 2 つの領域を返し、最も一致するターゲットを優先します。\n"
"JSON 2D リスト形式に厳密に従ってください:[[x1, y1, x2, y2], ...]\n"
"各座標セット:[左上の x, 左上の y, 右下の x, 右下の y]\n"
"元の画像の絶対ピクセル座標を使用し、(0,0) は左上隅、X 軸は右向き、Y 軸は下向きです。\n"
"領域が 1 つしかない場合でも、2D リストを使用する必要があります:[[x1, y1, x2, y2]]\n"
"JSON リストのみを返し、他のコンテンツは返さないでください。"
)
messages = [
{'role': 'user',
'content': [
{'image': image},
{'text': full_prompt}
]}
]
response = MultiModalConversation.call(
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='qwen3.6-plus',
messages=messages,
)
text = response.output.choices[0].message.content[0]["text"]
text = text.replace("```json", "").replace("```", "").strip()
coords = json.loads(text)
# モデルが 1D リスト [x1,y1,x2,y2] を返す場合を処理する
if coords and not isinstance(coords[0], list):
coords = [coords]
# 座標変換のために画像のディメンションを取得する
if image.startswith("file://"):
local_path = image[len("file://"):]
img = Image.open(local_path)
else:
tmp_path = "temp_bbox_image"
urllib.request.urlretrieve(image, tmp_path)
img = Image.open(tmp_path)
width, height = img.size
# モデルの正規化された座標 [0, 999] を絶対ピクセル座標に変換する
bbox_list = []
for box in coords:
bbox_list.append([
int(box[0] / 1000 * width),
int(box[1] / 1000 * height),
int(box[2] / 1000 * width),
int(box[3] / 1000 * height)
])
return bbox_list
# === 使用例 ===
image_url = "https://img.alicdn.com/imgextra/i3/O1CN01ewUWhg1eS3VqJ3wap_!!6000000003869-49-tps-2048-2048.webp"
# 名前でターゲットを選択
bbox = get_bbox_list(image_url, "コーヒーカップ") # [[x1, y1, x2, y2]]
# 位置の説明でターゲットを選択
bbox = get_bbox_list(image_url, "皿の中央にある果物") # [[x1, y1, x2, y2]]
# 領域を説明
bbox = get_bbox_list(image_url, "ラベンダーの鉢植え")
# 結果は bbox_list 配列の要素として使用できます
# 注:画像ごとに最大 2 つのバウンディングボックス
課金とレート制限
-
無料クォータと料金:モデルリストと料金。
-
レート制限については、Wanxiang をご参照ください。
-
課金:
- 料金は、正常に生成された画像ごとに適用されます。API が
task_statusとしてSUCCEEDEDを返した場合にのみ課金されます。 - モデルの呼び出しが失敗した場合や処理エラーが発生した場合、料金は発生せず、無料クォータも消費されません。
- 料金は、正常に生成された画像ごとに適用されます。API が
API リファレンス
各モデルでは、それぞれ異なるエンドポイントとリクエスト構造を使用します:
モデル | エンドポイント(シンガポールリージョンの例) |
|---|---|
| 同期 API: 非同期 API:
|
| 非同期 API:
|
wan2.7/wan2.6:messagesフォーマットを使用します。messages[].content配列で、imageパラメーターにイメージを、textパラメーターにプロンプトを渡します。wan2.5:input.images配列にイメージを、input.promptパラメーターにプロンプトを渡します。
"input": {
"messages": [
{
"role": "user",
"content": [
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"},
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"},
{"text": "画像 2 のグラフィティを画像 1 の車に吹き付けて"}
]
}
]
}
"input": {
"prompt": "イメージ 1 の目覚まし時計を、イメージ 2 の食卓にある花瓶の隣に配置",
"images": [
"https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp",
"https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
]
}
入出力パラメーターについては、「Wan2.7 - 画像生成と編集」、「Wan2.6 - 画像生成と編集」、「Wanxiang – 一般的な画像編集 2.5」をご参照ください。




































