すべてのプロダクト
Search
ドキュメントセンター

Alibaba Cloud Model Studio:Wanxiang – 一般画像編集 2.5

最終更新日:Jul 15, 2026

Wanxiang 一般画像編集 wan2.5 モデルは、テキストの命令のみで画像を編集および融合し、編集全体で主題の一貫性を維持します。

クイックスタート: ユーザーガイド

重要

Alibaba Cloud Model Studio は、中国 (北京) およびシンガポールリージョン向けにワークスペース固有のドメインをリリースしました。新しい専用ドメインは、推論リクエストに対して優れたパフォーマンスと高い安定性を提供します。新しいドメインへの移行を推奨します。

  • 中国 (北京): https://dashscope.aliyuncs.com から https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com

  • シンガポール: https://dashscope-intl.aliyuncs.com から https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

{WorkspaceId} はご利用のワークスペース ID で、Alibaba Cloud Model Studio コンソールの [ワークスペース詳細] ページで確認できます。既存のドメインも引き続き完全に機能します。

モデルの概要

モデルの機能

入力例

出力画像

単一画像の編集

damotest2023 Portrait photography outdoors fashionable beauty

a26b226d-f044-4e95-a41c-d1c0d301c30b

花柄のドレスを、襟と袖口に繊細な刺繍が施されたヴィンテージスタイルのレースガウンに置き換えます。

複数画像の融合

image

p1028883

画像 1 の目覚まし時計を、画像 2 の食卓にある花瓶の横に置きます。

モデル名

モデルの説明

出力画像の仕様

wan2.5-i2i-preview

Wanxiang 2.5 プレビュー

単一画像の編集と複数画像の融合をサポート

画像フォーマット:PNG。

画像解像度:

  • <a baseurl="t3137712_v2_2_0.xdita" data-node="6107277" data-root="85177" data-tag="xref" href="#2e0de6a5b1aw8" id="92c4acfccbmzm">parameters.size</a> パラメーターを使用して、出力画像の解像度を width*height (ピクセル単位) のフォーマットで指定します。

  • 解像度が指定されていない場合、デフォルトで合計 1280×1280 ピクセルになります。おおよその縦横比のルール:

    • 単一画像の入力の場合:入力画像の縦横比に一致します。

    • 複数画像の入力の場合:最後の入力画像の縦横比に一致します。

説明

API を呼び出す前に、ご利用のリージョンでサポートされているモデルと料金を確認してください。

前提条件

呼び出しを行う前に、API キーを取得し、API キーを環境変数としてエクスポートしてください。SDK を使用して呼び出しを行うには、DashScope SDK をインストールします。

重要

中国 (北京) とシンガポールリージョンでは、API キーリクエストエンドポイントがそれぞれ異なります。これらを相互に使用することはできません。リージョンをまたいだ呼び出しは、認証失敗またはサービスエラーにつながります。

HTTP API 呼び出し

画像の編集には 1~2 分かかるため、API は非同期呼び出しを使用します:タスクの作成 → 結果のポーリング

実際の実行時間は、キューの長さとサービスの負荷によって変動します。

ステップ 1:タスクを作成し、タスク ID を取得する

シンガポールリージョン: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis

北京リージョン: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis

{WorkspaceId} を実際のワークスペース ID に置き換えてください。

説明
  • タスクが作成された後、返された task_id を使用して結果をクエリします。task_id は 24 時間有効です。重複したタスクを作成しないでください。代わりに、ポーリングを使用して結果を取得してください。

  • 初心者向けのガイダンスについては、「Postman または cURL を使用して API を呼び出す」をご参照ください。

リクエストパラメーター

単一画像の編集

 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": "Replace the floral dress with a vintage-style lace gown featuring delicate embroidery on the collar and cuffs.",
        "images": [
            "https://img.alicdn.com/imgextra/i2/O1CN01vHOj4h28jOxUJPwY8_!!6000000007968-49-tps-1344-896.webp"
        ]
    },
    "parameters": {
        "prompt_extend": true,
        "n": 1
    }
}'

複数画像の融合

 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
    }
}'

リクエストヘッダー

Content-Type string (必須)

リクエストのコンテンツタイプ。application/json である必要があります。

Authorization string (必須)

Model Studio API キーでリクエストを認証します。例:Bearer sk-xxxx。

X-DashScope-Async string (必須)

非同期処理を有効にします。HTTP リクエストは非同期呼び出しのみをサポートします。enable である必要があります。

重要

このリクエストヘッダーがない場合、「current user api does not support synchronous calls」というエラーが返されます。

リクエストボディ

model string (必須)

モデル名。「サポートされているモデルと料金」をご参照ください。

値の例:wan2.5-i2i-preview。

input object (必須)

プロンプトや画像などの入力フィールド。

プロパティ

prompt string (必須)

生成される画像に含める要素や視覚的特徴を記述する肯定的なプロンプト。

中国語と英語をサポートします。最大:2000 文字 (各文字が 1 としてカウントされます)。超過分は切り捨てられます。

プロンプト作成のヒントについては、「テキストから画像へのプロンプトガイド」をご参照ください。

値の例:座っている陽気なオレンジ色の猫、リアルで詳細。

images array of string (必須)

画像 URL の配列。

  • 配列の最大長:3 (最大 3 枚の画像)。

  • 複数画像の入力の場合、順序が重要です。画像は配列のシーケンスに従います。

画像の要件:

  • フォーマット:JPEG、JPG、PNG (alpha チャンネルなし)、BMP、WEBP。

  • 解像度:幅と高さは 384~5000 ピクセルの間である必要があります。

  • ファイルサイズ:最大 10 MB。

サポートされている入力フォーマット:

  1. 公開アクセス可能な URL

    • プロトコル:HTTP または HTTPS。

    • 値の例:http://wanx.alicdn.com/material/20250318/stylization_all_1.jpeg

  2. Base64 エンコードされた画像文字列

    • フォーマット:data:{MIME_type};base64,{base64_data}

    • 例:data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (例のみ。完全な文字列を使用してください)。

    • Base64 エンコーディングの詳細:「画像入力メソッド」をご参照ください。

negative_prompt string (任意)

画像から除外する要素を記述する否定的なプロンプト。

中国語と英語をサポートします。最大:500 文字。超過分は切り捨てられます。

値の例:低解像度、エラー、最低品質、低品質、不完全、余分な指、不適切な比率。

parameters object (任意)

解像度、プロンプトリライト、ウォーターマークを制御します。

プロパティ

size string (任意)

出力画像の解像度を width×height フォーマットで設定します。デフォルト:1280×1280

  • 解像度範囲:合計ピクセル数が 768×768 から 1280×1280 の間。縦横比の範囲:1:4 から 4:1。

  • 値の例:1280×1280。

推奨される解像度と縦横比

  • 1280×1280: 1:1

  • 1024×1024: 1:1

  • 800×1200: 2:3

  • 1200×800: 3:2

  • 960×1280: 3:4

  • 1280×960: 4:3

  • 720×1280: 9:16

  • 1280×720: 16:9

  • 1344×576: 21:9

size が省略された場合、デフォルトで 1280×1280 ピクセルになり、おおよその縦横比は次のようになります:

  • 単一画像の入力の場合:入力画像の縦横比に一致します。

  • 複数画像の入力の場合:最後の入力画像の縦横比に一致します。

n integer (任意)

重要

n の値はコストに直接影響します。値が大きいほどコストが高くなります。呼び出す前に「モデルの料金」で料金を確認してください。

生成する画像の数。範囲:1~4。デフォルト:4。テスト中はコストを管理するために 1 に設定してください。

watermark boolean (任意)

右下隅に「AI Generated」のウォーターマークを追加します。

  • false: デフォルト。ウォーターマークなし。

  • true: ウォーターマークを追加。

prompt_extend boolean (任意)

LLM ベースのプロンプトリライトを有効にして画質を向上させます。レイテンシが追加されます。

  • true: デフォルト。リライトを有効にする。

  • false: リライトを無効にする。

値の例:true。

seed integer (任意)

乱数シード。有効範囲:[0, 2147483647]

省略した場合、ランダムなシードが生成されます。指定した場合、n 枚の各画像に n に基づいて連続したシードが割り当てられます。たとえば、n=4 の場合、シードは seed、seed+1、seed+2、seed+3 となります。

再現性を向上させるには、シード値を固定してください。

確率的な生成のため、同一のシードが同一の出力を保証するわけではありません。

レスポンスパラメーター

成功レスポンス

task_id を保存して、タスクのステータスと結果をクエリします。

{
    "output": {
        "task_status": "PENDING",
        "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
    },
    "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}

エラーレスポンス

タスクの作成に失敗しました。「エラーコード」をご参照ください。

{
    "code": "InvalidApiKey",
    "message": "No API-key provided.",
    "request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
}

output object

タスクの出力情報。

プロパティ

task_id string

タスク ID。24 時間クエリに有効です。

task_status string

タスクのステータス。

列挙値

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN:タスクが存在しないか、ステータスが不明です。

request_id string

追跡とトラブルシューティングのためのユニークなリクエスト識別子。

code string

エラーコード。失敗したリクエストに対してのみ返されます。「エラーコード」をご参照ください。

message string

詳細なエラーメッセージ。失敗したリクエストに対してのみ返されます。「エラーコード」をご参照ください。

ステップ 2:タスク ID を使用して結果をクエリする

シンガポール

GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

呼び出す際、{WorkspaceId} を実際のワークスペース ID に置き換えてください。

中国 (北京)

GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}

呼び出す際、{WorkspaceId} を実際のワークスペース ID に置き換えてください。

説明
  • ポーリングの推奨事項:画像生成には時間がかかります。10 秒などの適切な間隔でポーリングメカニズムを使用してください。

  • タスク状態の遷移:PENDING → RUNNING → SUCCEEDED または FAILED。

  • 結果リンク:タスクが成功すると、24 時間有効な画像 URL が返されます。画像をダウンロードし、OSS などの永続ストレージに保存してください。

リクエストパラメーター

タスク結果のクエリ

86ecf553-d340-4e21-xxxxxxxxx を実際の task_id に置き換えてください。

API キーはリージョンごとに異なります。詳細については、「API キーの取得」をご参照ください。
中国 (北京) リージョンのモデルを使用する場合、base_urlhttps://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx に置き換えてください。ここで、{WorkspaceId} は実際のワークスペース ID です。
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
リクエストヘッダー

Authorization string (必須)

Model Studio API キーでリクエストを認証します。例:Bearer sk-xxxx。

URL パスパラメーター

task_id string (必須)

タスクの ID。

レスポンスパラメーター

タスク成功

画像 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": "Replace the floral dress with a vintage-style lace gown featuring delicate embroidery on the collar and cuffs.",
                "actual_prompt": "Replace the pink pleated dress with a vintage-style lace gown featuring delicate embroidery on the collar and cuffs. Keep the person’s hairstyle, makeup, and pose unchanged. Match the original image’s soft tones and classical atmosphere.",
                "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
    }
}

タスク失敗

タスクが失敗すると、task_status は FAILED となり、エラーコードとメッセージが表示されます。「エラーコード」をご参照ください。

{
    "request_id": "e5d70b02-ebd3-98ce-9fe8-759d7d7b107d",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-xxxxxx",
        "task_status": "FAILED",
        "code": "InvalidParameter",
        "message": "xxxxxx",
        "task_metrics": {
            "TOTAL": 4,
            "SUCCEEDED": 0,
            "FAILED": 4
        }
    }
}

部分的な失敗

モデルはタスクごとに複数の画像を生成できます。少なくとも 1 つが成功した場合、タスクのステータスは SUCCEEDED となり、成功した画像の URL が返されます。失敗した画像には失敗理由が含まれます。使用状況の統計は成功した結果のみをカウントします。「エラーコード」をご参照ください。

{
    "request_id": "85eaba38-0185-99d7-8d16-xxxxxx",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-xxxxxx",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/123/a1.png"
            },
            {
                "code": "InternalError.Timeout",
                "message": "An internal timeout error has occurred during execution, please try again later or contact service support."
            }
        ],
        "task_metrics": {
            "TOTAL": 2,
            "SUCCEEDED": 1,
            "FAILED": 1
        }
    },
    "usage": {
        "image_count": 1
    }
}

タスククエリの期限切れ

task_id は 24 時間有効です。この期間を過ぎると、クエリは以下のエラーを返します。

{
    "request_id": "a4de7c32-7057-9f82-8581-xxxxxx",
    "output": {
        "task_id": "502a00b1-19d9-4839-a82f-xxxxxx",
        "task_status": "UNKNOWN"
    }
}

output object

タスクの出力情報。

プロパティ

task_id string

タスク ID。24 時間クエリに有効です。

task_status string

タスクのステータス。

列挙値

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN:タスクが存在しないか、ステータスが不明です。

submit_time string

タスクが送信された時刻。時刻は UTC+8 で、フォーマットは YYYY-MM-DD HH:mm:ss.SSS です。

scheduled_time string

タスクが実行された時刻。時刻は UTC+8 で、フォーマットは YYYY-MM-DD HH:mm:ss.SSS です。

end_time string

タスクが完了した時刻。時刻は UTC+8 で、フォーマットは YYYY-MM-DD HH:mm:ss.SSS です。

results array of object

画像 URL、プロンプト、部分的な失敗のエラー詳細を含むタスク結果のリスト。

プロパティ

orig_prompt string

元の入力プロンプト。リクエストパラメーター prompt に対応します。

actual_prompt string

プロンプトリライトが有効な場合に使用される最適化されたプロンプト。無効な場合は返されません。

url string

生成された画像の URL。

code string

失敗した画像のエラーコード。部分的な失敗の場合にのみ返されます。

message string

失敗した画像のエラーメッセージ。部分的な失敗の場合にのみ返されます。

task_metrics object

タスク結果の統計。

プロパティ

TOTAL integer

タスクの総数。

SUCCEEDED integer

成功したタスクの数。

FAILED integer

失敗したタスクの数。

code string

エラーコード。失敗したリクエストに対してのみ返されます。「エラーコード」をご参照ください。

message string

詳細なエラーメッセージ。失敗したリクエストに対してのみ返されます。「エラーコード」をご参照ください。

usage object

使用状況の統計。成功した結果のみをカウントします。

プロパティ

image_count integer

正常に生成された画像の数。課金:コスト = 画像数 × 単価。

request_id string

追跡とトラブルシューティングのためのユニークなリクエスト識別子。

DashScope SDK 呼び出し

SDK パラメーターは、各言語に合わせてラップされた HTTP API 呼び出しと一致します。

画像の編集には 30~60 秒かかります。SDK は非同期 HTTP フローをラップし、同期呼び出しと非同期呼び出しの両方をサポートします。

実際の実行時間は、キューの長さとサービスの負荷によって変動します。

Python SDK 呼び出し

重要

DashScope Python SDK のバージョンが少なくとも 1.25.2 であることを確認してください。

古いバージョンでは「url error, please check url!」などのエラーが発生する可能性があります。「SDK のインストールまたはアップグレード」を使用して更新してください。

同期呼び出し

リクエスト例

この例では、パブリック 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/ja/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
    }
}

非同期呼び出し

この例では、画像入力にパブリック 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/ja/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()
レスポンス例

1. タスク作成時のレスポンス

{
	"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
}

2. タスク結果クエリ時のレスポンス

画像 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 SDK 呼び出し

重要

DashScope Java SDK のバージョンが少なくとも 2.22.2 であることを確認してください。

古いバージョンでは「url error, please check url!」などのエラーが発生する可能性があります。「SDK のインストールまたはアップグレード」を使用して更新してください。

同期呼び出し

リクエスト例

この例では、パブリック URL、Base64 エンコーディング、ローカルファイルパスの 3 つの画像入力メソッドをサポートしています。

// 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/ja/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() {
        // パラメーターを設定
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        parameters.put("watermark", false);
        parameters.put("seed", 12345);

        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("")
                        .parameters(parameters)
                        .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
    }
}

非同期呼び出し

この例では、画像入力にパブリック 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.HashMap;
import java.util.List;
import java.util.Map;

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/ja/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() {
        // パラメーターを設定
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        parameters.put("watermark", false);
        parameters.put("seed", 12345);

        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("")
                        .parameters(parameters)
                        .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();
    }
}
レスポンス例

1. タスク作成時のレスポンス

{
	"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
	"output": {
		"task_id": "7277e20e-aa01-4709-xxxxxxxx",
		"task_status": "PENDING"
	}
}

2. タスク結果クエリ時のレスポンス

画像 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
    }
}

制限事項

  • データ保持:タスク ID と画像 URL はどちらも 24 時間後に期限切れになります。期限切れ後はクエリやダウンロードはできません。

  • コンテンツモデレーション:すべてのプロンプト、入力画像、出力画像はコンテンツモデレーションを受けます。禁止されたコンテンツを含むリクエストは、「IPInfringementSuspect」や「DataInspectionFailed」などのエラーを返します。詳細については、「エラー情報」をご参照ください。

エラーコード

モデルの呼び出しが失敗し、エラーメッセージが返された場合は、「エラーコード」で解決策をご確認ください。

よくある質問

Q:以前に General Image Editing 2.1 を使用していましたが、wan2.5 を使用するために SDK 呼び出しを変更する必要がありますか?

A:はい — バージョン間でパラメーターの設計が異なります:

  • General Image Editing 2.1promptfunction の両方のパラメーターが必要です。

  • General Image Editing 2.5のみ prompt が必要です。すべての編集をテキストで記述します。function パラメーターはサポートされなくなり、不要です。

Q:モデルの使用状況メトリックはどのように表示しますか?

A:モデルの呼び出しが完了してから 1 時間後、モデルテレメトリ (シンガポール)モデルテレメトリ (北京) ページに移動して、呼び出し回数や成功率などのメトリックを表示します。ステップバイステップのガイダンスについては、「モデルの呼び出し履歴を表示する方法」をご参照ください。