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

Alibaba Cloud Model Studio:Wan2.7 - 画像生成と編集

最終更新日:Jul 15, 2026

Wan2.7-Image は、テキストからの画像生成、テキストからの画像セット生成、画像からの画像セット生成、画像編集、複数画像の参照生成をサポートしています。

モデル概要

モデル

説明

出力画像の仕様

wan2.7-image-pro

Wan 2.7 画像 Pro。テキストからの画像生成 (画像セットは除く) で 4K 出力をサポートします。

画像フォーマット:PNG。

画像の解像度とディメンションについては、size パラメーターをご参照ください。

wan2.7-image

Wan 2.7 画像。より高速な生成。

説明

モデルを呼び出す前に、モデルリストと価格でリージョンごとのモデルの可用性を確認してください。

前提条件

API キーを取得し、API キーを環境変数としてエクスポートします。

重要

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

HTTP 同期

単一のリクエストで結果を返します。ほとんどのユースケースで推奨されます。

シンガポール

POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

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

北京

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

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

リクエストパラメーター

テキストからの画像生成

wan2.7-image-pro モデルは、テキストからの画像生成のみ 4K 解像度をサポートします。画像編集と画像セット生成は最大 2K 解像度までサポートします。
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": [
                        {"text": "精巧な窓、美しい木製のドア、そして花が飾られた花屋"}
                    ]
                }
            ]
        },
        "parameters": {
            "size": "2K",
            "n": 1,
            "watermark": false,
            "thinking_mode": true
        }
    }'
    

画像編集

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/20251229/pjeqdf/car.webp"},
                        {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/20251229/xsunlm/paint.webp"},
                        {"text": "画像 2 のグラフィティを画像 1 の車にスプレーペイントします"}
                    ]
                }
            ]
        },
        "parameters": {
            "size": "2K",
            "n": 1,
            "watermark": false
        }
    }'
    

インタラクティブな編集

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

画像セット生成

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": [
                        {"text": "同じ野良の茶トラ猫を記録した映画のような画像群。特徴は全体を通して一貫している必要があります。最初の画像:春、茶トラ猫は満開の桜の木の間を縫うように歩きます。2番目の画像:夏、茶トラ猫は古い通りの木陰で涼んでいます。3番目の画像:秋、茶トラ猫は金色の落ち葉で覆われた地面を踏みしめます。4番目の画像:冬、茶トラ猫は雪の上を歩き、足跡を残します。"}
                    ]
                }
            ]
        },
        "parameters": {
            "enable_sequential": true,
            "n": 4,
            "size": "2K"
        }
    }'
    

ヘッダー

Content-Type string (必須)

リクエストのコンテンツタイプとして application/json を指定する必要があります。

Authorization string (必須)

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

リクエストボディ

model string (必須)

モデル名。有効な値:wan2.7-image-prowan2.7-image

input object (必須)

入力オブジェクト。

プロパティ

messages array (必須)

リクエストコンテンツの配列。シングルターンの会話のみサポートされています。

プロパティ

role string (必須)

メッセージのロール。 user である必要があります。

content array (必須)

メッセージコンテンツの配列。

プロパティ

text string

テキストプロンプト。中国語と英語をサポートします。最大 5,000 文字。各文字、英字、数字、記号は 1 文字としてカウントされます。超過した文字は切り捨てられます。

image string

入力画像の URL または Base64 エンコードされた文字列。

画像の制限:

  • 画像フォーマット:JPEG、JPG、PNG (アルファチャンネルはサポートされていません)、BMP、WEBP。

  • 画像解像度:幅と高さは 240 から 8,000 ピクセルの間である必要があります。アスペクト比は 1:8 から 8:1 の間でなければなりません。

  • ファイルサイズ:20 MB 以下。

画像数の制限:

  • 0 から 9 枚の画像を入力できます。

  • 複数のイメージを入力する場合、複数の image オブジェクトを content 配列で渡す必要があります。イメージの順序は、配列内のオブジェクトの順序によって決まります。

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

  1. パブリックにアクセス可能な URL を使用する

    • HTTP または HTTPS プロトコルをサポートします。

    • 例:http://wanx.alicdn.com/material/xxx.jpeg

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

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

    • 例:data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (これは説明用です。完全な文字列を渡す必要があります。)

    • 詳細については、画像入力メソッドをご参照ください。

parameters object (任意)

モデルのパラメーター設定。

プロパティ

bbox_list List[List[List[int]]] (任意)

インタラクティブな編集のためのバウンディングボックス領域。

  • リストの長さは入力画像の数と一致する必要があります。画像に編集が不要な場合は、対応する位置に空のリスト [] を渡します。

  • 座標フォーマット:[x1, y1, x2, y2] (左上の x、左上の y、右下の x、右下の y)。元の画像の絶対ピクセル座標を使用します。左上の座標は (0, 0) です。

  • 1 つの画像は最大 2 つのバウンディングボックスをサポートします。

例:3 つの画像を入力し、2 番目の画像にはバウンディングボックスがなく、1 番目の画像には 2 つのバウンディングボックスがある場合:

[
  [[0, 0, 12, 12], [25, 25, 100, 100]],  # 画像 1 (2 つのボックス)
  [],                                    # 画像 2 (ボックスなし)
  [[10, 10, 50, 50]]                     # 画像 3 (1 つのボックス)
]

enable_sequential boolean (任意)

画像生成モードを制御します:

  • false (デフォルト):デフォルトの出力モード。

  • true:画像セット出力モード。

size string (任意)

出力画像の解像度。相互に排他的な 2 つのメソッドをサポートします:

モデル:wan2.7-image-pro

  • メソッド 1:出力画像の解像度を指定 (推奨)

    • 1K、2K (デフォルト)、4K の仕様をサポートします。

    • 適用範囲

      • テキストからの画像生成 (画像入力なし、画像セット生成用ではない):1K、2K、4K をサポートします。

      • その他のシナリオ:1K と 2K をサポートします。

    • 各仕様の総ピクセル数:1K:1024×1024、2K:2048×2048、4K:4096×4096

    • 画像のアスペクト比

      • 画像が入力された場合:出力のアスペクト比は入力画像 (複数の画像が入力された場合は最後の画像) と一致し、選択された解像度にスケーリングされます。

      • 画像が入力されていない場合:出力は正方形の画像になります。

  • メソッド 2:生成される画像の幅と高さをピクセルで指定

    • テキストからの画像生成:総ピクセル数は 768×768 から 4096×4096 の間です。アスペクト比は 1:8 から 8:1 の間です。

    • その他のシナリオ:総ピクセル数は 768×768 から 2048×2048 の間です。アスペクト比は 1:8 から 8:1 の間です。

モデル:wan2.7-image

  • メソッド 1:出力画像の解像度を指定 (推奨)

    • 1K と 2K (デフォルト) の仕様をサポートします。4K はサポートされていません。

  • メソッド 2:生成される画像の幅と高さをピクセルで指定

    • すべてのシナリオで、総ピクセル数は 768×768 から 2048×2048 の間です。アスペクト比は 1:8 から 8:1 の間です。

出力画像のピクセル値は、指定された値とわずかに異なる場合があります。

n int (任意)

重要

n パラメーターはコストに直接影響します:単価 × 正常に生成された画像の数。呼び出す前に、モデルの価格設定を確認してください。

  • 画像セットモードが無効の場合、この値は生成する画像の数を表します。範囲は 1 から 4 です。デフォルトは 1 です。

  • 画像セットモードが有効の場合、この値は生成する画像の最大数を表します。範囲は 1 から 12 です。デフォルトは 12 です。実際の数はモデルによって決定され、n を超えることはありません。

thinking_mode boolean (任意)

思考モードを有効にします。デフォルトは true です。このパラメーターは、画像セットモードが無効で、画像が入力されていない場合にのみ有効です。有効にすると、モデルは推論能力を向上させて出力品質を改善しますが、生成時間が増加します。

color_palette array (任意)

カスタムカラーテーマ。各オブジェクトが 16 進数カラーと比率を持つオブジェクトの配列。3 から 10 色を含める必要があります。8 色を推奨します。

これは、画像セットモードが無効 (enable_sequential=false) の場合にのみ利用可能です。

プロパティ

hex string (必須)

16 進数 (HEX) 形式のカラー値。

ratio string (必須)

色のパーセンテージ。小数点以下 2 桁まで正確である必要があります (例:"25.00%")。すべての比率値の合計は 100.00% でなければなりません。

クリックして入力例を表示

"color_palette": [
    {
        "hex": "#C2D1E6",
        "ratio": "23.51%"
    },
    {
        "hex": "#CDD8E9",
        "ratio": "20.13%"
    },
    {
        "hex": "#B5C8DB",
        "ratio": "15.88%"
    },
    {
        "hex": "#C0B5B4",
        "ratio": "13.27%"
    },
    {
        "hex": "#DAE0EC",
        "ratio": "10.11%"
    },
    {
        "hex": "#636574",
        "ratio": "8.93%"
    },
    {
        "hex": "#CACAD2",
        "ratio": "5.55%"
    },
    {
        "hex": "#CBD4E4",
        "ratio": "2.62%"
    }
]

watermark bool (任意)

画像の右下隅に固定テキスト「AI Generated」のウォーターマークラベルを追加します。

  • false (デフォルト)

  • true

seed integer (任意)

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

同じ seed を使用すると、類似した出力が得られます。省略した場合、アルゴリズムはランダムなシードを使用します。

注:画像生成は確率的です。同じ seed を使用しても、結果が異なる場合があります。

レスポンスパラメーター

タスクの正常な実行

タスクデータ (タスクステータスと画像 URL) は 24 時間のみ保持され、その後自動的にパージされます。生成された画像は速やかに保存してください。

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

タスクの異常な実行

タスクが失敗した場合、レスポンスの code および message フィールドがエラーの原因を示します。エラーコードをご参照ください。

{
    "request_id": "a4d78a5f-655f-9639-8437-xxxxxx",
    "code": "InvalidParameter",
    "message": "num_images_per_prompt must be 1"
}

output object

タスクの出力情報。

プロパティ

choices array

モデルによって生成された出力コンテンツ。

プロパティ

finish_reason string

タスクが停止した理由。stop は自然な完了を示します。

message object

モデルから返されたメッセージ。

プロパティ

role string

メッセージのロール。常に assistant です。

content array

プロパティ

type string

値:image。

image string

生成された画像の URL。フォーマット:PNG。

リンクは 24 時間有効です。速やかに画像をダウンロードしてください。

finished boolean

タスクが完了したかどうかを示します。デフォルト:false。

usage object

リクエストの使用統計。成功した結果のみがカウントされます。

プロパティ

image_count integer

生成された画像の数。

size string

生成された画像の解像度。例:1376*768。

input_tokens integer

入力トークンの数 (課金対象外)。課金は画像の数に基づきます。

output_tokens integer

出力トークンの数 (課金対象外)。課金は画像の数に基づきます。

total_tokens integer

トークンの総数 (課金対象外)。課金は画像の数に基づきます。

request_id string

トレースとトラブルシューティングのための一意のリクエスト識別子。

code string

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

message string

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

HTTP 非同期

長時間のタスクに最適です。タスクを送信し、その後ステータスと結果をポーリングします。

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

シンガポール

POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation

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

北京

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation

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

リクエストパラメーター

テキストからの画像生成

wan2.7-image-pro モデルは、テキストからの画像生成のみ 4K 解像度をサポートします。画像編集と画像セット生成は最大 2K 解像度までサポートします。
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": [
                        {"text": "精巧な窓、美しい木製のドア、そして花が飾られた花屋"}
                    ]
                }
            ]
        },
        "parameters": {
            "size": "2K",
            "n": 1,
            "watermark": false,
            "thinking_mode": true
        }
    }'
    

画像編集

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

インタラクティブな編集

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

画像セット生成

wan2.7-image-pro モデルは、画像セット生成で最大 2K 解像度をサポートします。
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": [
                        {"text": "同じ野良の茶トラ猫を特集した映画のような写真セット。その特徴はすべての画像で一貫している必要があります。最初の画像:春、猫は満開の桜の木の間を縫うように歩きます。2番目の画像:夏、猫は古い通りの木陰で涼んでいます。3番目の画像:秋、猫は金色の落ち葉で覆われた地面を踏みしめます。4番目の画像:冬、猫は雪の上を歩き、足跡を残します。"}
                    ]
                }
            ]
        },
        "parameters": {
            "enable_sequential": true,
            "n": 4,
            "size": "2K"
        }
    }'
    

ヘッダー

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.7-image-prowan2.7-image

input object (必須)

入力オブジェクト。

プロパティ

messages array (必須)

リクエストコンテンツの配列。シングルターンの会話のみサポートされています。

プロパティ

role string (必須)

メッセージのロール。値は user である必要があります。

content array (必須)

メッセージコンテンツの配列。

プロパティ

text string

テキストプロンプト。中国語と英語をサポートします。最大 5,000 文字。各文字、英字、数字、記号は 1 文字としてカウントされます。超過した文字は切り捨てられます。

image string

入力画像の URL または Base64 エンコードされた文字列。

画像の制限:

  • 画像フォーマット:JPEG、JPG、PNG (アルファチャンネルはサポートされていません)、BMP、WEBP。

  • 画像解像度:幅と高さは 240 から 8,000 ピクセルの間である必要があります。アスペクト比は 1:8 から 8:1 の間でなければなりません。

  • ファイルサイズ:20 MB 以下。

画像数の制限:

  • 0 から 9 枚の画像を入力できます。

  • 複数のイメージを入力する場合、複数の image オブジェクトを content 配列に渡す必要があります。配列内のオブジェクトの順序が、イメージの順序を決定します。

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

  1. パブリックにアクセス可能な URL を使用する

    • HTTP または HTTPS プロトコルをサポートします。

    • 例:http://wanx.alicdn.com/material/xxx.jpeg

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

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

    • 例:data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (これは説明用です。完全な文字列を渡す必要があります。)

    • 詳細については、画像入力メソッドをご参照ください。

parameters object (任意)

モデルのパラメーター設定。

プロパティ

bbox_list List[List[List[int]]] (任意)

インタラクティブな編集のためのバウンディングボックス領域。

  • リストの長さは入力画像の数と一致する必要があります。画像に編集が不要な場合は、対応する位置に空のリスト [] を渡します。

  • 座標フォーマット:[x1, y1, x2, y2] (左上の x、左上の y、右下の x、右下の y)。元の画像の絶対ピクセル座標を使用します。左上の座標は (0, 0) です。

  • 1 つの画像は最大 2 つのバウンディングボックスをサポートします。

例:3 つの画像を入力し、2 番目の画像にはバウンディングボックスがなく、1 番目の画像には 2 つのバウンディングボックスがある場合:

[
  [[0, 0, 12, 12], [25, 25, 100, 100]],  # 画像 1 (2 つのボックス)
  [],                                    # 画像 2 (ボックスなし)
  [[10, 10, 50, 50]]                     # 画像 3 (1 つのボックス)
]

enable_sequential boolean (任意)

画像生成モードを制御します:

  • false (デフォルト):デフォルトの出力モード。

  • true:画像セット出力モード。

size string (任意)

出力画像の解像度。相互に排他的な 2 つのメソッドをサポートします:

モデル:wan2.7-image-pro

  • メソッド 1:出力画像の解像度を指定 (推奨)

    • 1K、2K (デフォルト)、4K の仕様をサポートします。

    • 適用範囲

      • テキストからの画像生成 (画像入力なし、画像セット生成用ではない):1K、2K、4K をサポートします。

      • その他のシナリオ:1K と 2K をサポートします。

    • 各仕様の総ピクセル数:1K:1024×1024、2K:2048×2048、4K:4096×4096

    • 画像のアスペクト比

      • 画像が入力された場合:出力のアスペクト比は入力画像 (複数の画像が入力された場合は最後の画像) と一致し、選択された解像度にスケーリングされます。

      • 画像が入力されていない場合:出力は正方形の画像になります。

  • メソッド 2:生成される画像の幅と高さをピクセルで指定

    • テキストからの画像生成:総ピクセル数は 768×768 から 4096×4096 の間です。アスペクト比は 1:8 から 8:1 の間です。

    • その他のシナリオ:総ピクセル数は 768×768 から 2048×2048 の間です。アスペクト比は 1:8 から 8:1 の間です。

モデル:wan2.7-image

  • メソッド 1:出力画像の解像度を指定 (推奨)

    • 1K と 2K (デフォルト) の仕様をサポートします。4K はサポートされていません。

  • メソッド 2:生成される画像の幅と高さをピクセルで指定

    • すべてのシナリオで、総ピクセル数は 768×768 から 2048×2048 の間です。アスペクト比は 1:8 から 8:1 の間です。

出力画像のピクセル値は、指定された値とわずかに異なる場合があります。

n int (任意)

重要

n パラメーターはコストに直接影響します:単価 × 正常に生成された画像の数。呼び出す前に、モデルの価格設定を確認してください。

  • 画像セットモードが無効の場合、この値は生成する画像の数を表します。範囲は 1 から 4 です。デフォルトは 1 です。

  • 画像セットモードが有効の場合、この値は生成する画像の最大数を表します。範囲は 1 から 12 です。デフォルトは 12 です。実際の数はモデルによって決定され、n を超えることはありません。

thinking_mode boolean (任意)

思考モードを有効にします。デフォルトは true です。このパラメーターは、画像セットモードが無効で、画像が入力されていない場合にのみ有効です。有効にすると、モデルは推論能力を向上させて出力品質を改善しますが、生成時間が増加します。

color_palette array (任意)

カスタムカラーテーマ。各オブジェクトが 16 進数カラーと比率を持つオブジェクトの配列。3 から 10 色を含める必要があります。8 色を推奨します。

これは、画像セットモードが無効 (enable_sequential=false) の場合にのみ利用可能です。

プロパティ

hex string (必須)

16 進数 (HEX) 形式のカラー値。

ratio string (必須)

色のパーセンテージ。小数点以下 2 桁まで正確である必要があります (例:"25.00%")。すべての比率値の合計は 100.00% でなければなりません。

クリックして入力例を表示

"color_palette": [
    {
        "hex": "#C2D1E6",
        "ratio": "23.51%"
    },
    {
        "hex": "#CDD8E9",
        "ratio": "20.13%"
    },
    {
        "hex": "#B5C8DB",
        "ratio": "15.88%"
    },
    {
        "hex": "#C0B5B4",
        "ratio": "13.27%"
    },
    {
        "hex": "#DAE0EC",
        "ratio": "10.11%"
    },
    {
        "hex": "#636574",
        "ratio": "8.93%"
    },
    {
        "hex": "#CACAD2",
        "ratio": "5.55%"
    },
    {
        "hex": "#CBD4E4",
        "ratio": "2.62%"
    }
]

watermark bool (任意)

画像の右下隅に固定テキスト「AI Generated」のウォーターマークラベルを追加します。

  • false (デフォルト)

  • true

seed integer (任意)

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

同じ seed を使用すると、類似した出力が得られます。省略した場合、アルゴリズムはランダムなシードを使用します。

注:画像生成は確率的です。同じ seed を使用しても、結果が異なる場合があります。

レスポンスパラメーター

成功したレスポンス

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}

北京

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

リクエストパラメーター

タスク結果のクエリ

{task_id} を、前の API 呼び出しで返された task_id の値に置き換えます。task_id は 24 時間クエリに有効です。

curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
ヘッダー

Authorization string (必須)

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

パスパラメーター

task_id string (必須)

タスクの ID。

レスポンスパラメーター

タスクの正常な実行

タスクデータ (タスクステータスと画像 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
    }
}

タスクの異常な実行

タスクが失敗した場合、レスポンスの code および message フィールドがエラーの原因を示します。エラーコードをご参照ください。

{
    "request_id": "a4d78a5f-655f-9639-8437-xxxxxx",
    "code": "InvalidParameter",
    "message": "num_images_per_prompt must be 1"
}

output object

タスクの出力情報。

プロパティ

task_id string

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

task_status string

タスクのステータス。

列挙値

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

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

ポーリング中の状態遷移:

  • PENDING → RUNNING → SUCCEEDED または FAILED。

  • 初期クエリのステータスは通常 PENDING または RUNNING です。

  • ステータスが SUCCEEDED に変わると、レスポンスには生成された画像の URL が含まれます。

  • ステータスが FAILED の場合は、エラーメッセージを確認してタスクを再試行してください。

submit_time string

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

scheduled_time string

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

end_time string

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

finished boolean

タスクが完了したかどうかを示します。デフォルト:false。

choices array

モデルによって生成された出力コンテンツ。

プロパティ

finish_reason string

タスクが停止した理由。stop は自然な完了を示します。

message object

モデルから返されたメッセージ。

プロパティ

role string

メッセージのロール。常に assistant です。

content array

プロパティ

type string

値:text、image。

text string

生成されたテキスト。

image string

生成された画像の URL。フォーマット:PNG。

リンクは 24 時間有効です。速やかに画像をダウンロードしてください。

usage object

リクエストの使用統計。成功した結果のみがカウントされます。

プロパティ

image_count integer

生成された画像の数。

size string

生成された画像の解像度。例:1376*768。

input_tokens integer

入力トークンの数 (課金対象外)。課金は画像の数に基づきます。

output_tokens integer

出力トークンの数 (課金対象外)。課金は画像の数に基づきます。

total_tokens integer

トークンの総数 (課金対象外)。課金は画像の数に基づきます。

request_id string

トレースとトラブルシューティングのための一意のリクエスト識別子。

code string

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

message string

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

Python SDK

SDK のパラメーター名は、HTTP API とほぼ一致しています。

画像生成タスクには時間がかかることがあるため、SDK は HTTP 非同期ワークフローをラップしています。同期呼び出しと非同期呼び出しの両方がサポートされています。

タスクの所要時間は、キューの長さとサービスのステータスに依存します。
重要

DashScope Python SDK のバージョンが 1.25.15 以降であることを確認してください。更新するには、SDK のインストールをご参照ください。

base_url と API キーは両方ともリージョン固有です。次の例では、シンガポールリージョンを使用しています:

シンガポール

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

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

中国 (北京)

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

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

画像編集

同期呼び出し

リクエスト例
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/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("サポートされていない、または認識されない画像形式です")
    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/20251229/pjeqdf/car.webp"
image_2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/20251229/xsunlm/paint.webp"

# [メソッド 2] ローカルファイルを使用 (絶対パスと相対パスをサポート)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"

# [メソッド 3] Base64 エンコードされた画像を使用
# image_1 = encode_file("/path/to/your/car.png")
# image_2 = encode_file("/path/to/your/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
    }
}

非同期呼び出し

リクエスト例
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/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("サポートされていない、または認識されない画像形式です。")
    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/20251229/pjeqdf/car.webp"
image_2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/20251229/xsunlm/paint.webp"

# [メソッド 2] ローカルファイルを使用 (絶対パスと相対パスをサポート)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"

# [メソッド 3] Base64 エンコードされた画像を使用
# image_1 = encode_file("/path/to/your/car.png")
# image_2 = encode_file("/path/to/your/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)
レスポンス例
  1. タスク作成のレスポンス例

    {
        "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
        }
    }
  2. タスク結果クエリのレスポンス例

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

画像セット生成

同期呼び出し

リクエスト例
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/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("サポートされていない、または認識されない画像形式です")
    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://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp"

# [メソッド 2] ローカルファイルを使用 (絶対パスと相対パスの両方をサポート)
# image_1 = "file:///path/to/your/image.png"

# [メソッド 3] Base64 エンコードされた画像を使用
# image_1 = encode_file("/path/to/your/image.png")

message = Message(
    role="user",
    content=[
        {
            "text": "同じ野良の茶トラ猫を特集した映画のような画像シーケンス。その特徴はすべての画像で一貫している必要があります。最初の画像:春、茶トラ猫は満開の桜の木の間を縫うように歩きます。2番目の画像:夏、茶トラ猫は古い通りの木陰で涼んでいます。3番目の画像:秋、茶トラ猫は金色の落ち葉の絨毯の上を歩きます。4番目の画像:冬、茶トラ猫は雪の上を歩きながら足跡を残します。"
        }
        # 画像から画像へのシーケンス生成用:以下の行のコメントを解除し、上のプレーンテキストをコメントアウトします。
        # {"text": "参照画像のスタイルに基づいて四季の画像シーケンスを生成します"},
        # {"image": image_1}
    ],
)

print("----同期呼び出し、しばらくお待ちください----")
rsp = ImageGeneration.call(
    model="wan2.7-image-pro",
    api_key=api_key,
    messages=[message],
    enable_sequential=True,
    n=4,
    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": "56e318fd-ed60-99e8-8ca1-cdef25ca4xxx",
    "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"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "audio": null,
        "finished": true
    },
    "usage": {
        "input_tokens": 720,
        "output_tokens": 11,
        "characters": 0,
        "image_count": 4,
        "size": "2048*2048",
        "total_tokens": 731
    }
}

非同期呼び出し

リクエスト例
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"

# DASHSCOPE_API_KEY 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください: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 データ URI スキームは 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://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp"

# [メソッド 2] ローカルファイルを使用 (絶対パスと相対パスがサポートされています)
# image_1 = "file:///path/to/your/image.png"

# [メソッド 3] Base64 エンコードされた画像を使用
# image_1 = encode_file("/path/to/your/image.png")

def main():
    message = Message(
        role="user",
        content=[
            {
                "text": "同じ野良の茶トラ猫を記録した映画のような画像シーケンス。その特徴はすべての画像で一貫している必要があります。画像 1:春、猫は満開の桜の木の間を縫うように歩きます。画像 2:夏、猫は古い通りの木陰で涼んでいます。画像 3:秋、猫は金色の落ち葉の絨毯の上を歩きます。画像 4:冬、猫は雪の上を歩き、足跡を残します。"
            }
            # 画像から画像へのシーケンス生成シナリオ:以下の行のコメントを解除し、上のプレーンテキストをコメントアウトします。
            # {"text": "参照画像のスタイルに基づいて四季の画像シーケンスを生成します。"},
            # {"image": image_1}
        ],
    )

    # 非同期タスクを送信する
    print("非同期タスクを送信中...")
    response = ImageGeneration.async_call(
        model="wan2.7-image-pro",
        api_key=api_key,
        messages=[message],
        enable_sequential=True,
        n=4,
        size="2K",  # wan2.7-image-pro は、テキストから画像へのシナリオでのみ 4K 解像度をサポートします。画像編集と画像シーケンス生成は最大 2K 解像度までサポートします。
    )

    if response.status_code == 200:
        print(f"タスクが正常に送信されました。タスク ID:{response.output.task_id}")

        # タスクの完了を待つ
        status = ImageGeneration.wait(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:
            print(f"タスクが失敗しました。ステータス:{status.output.task_status}")
    else:
        print(f"タスクの作成に失敗しました:{response.code} - {response.message}")

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"エラー:{e}")
レスポンス例
  1. タスク作成のレスポンス例

    {
        "status_code": 200,
        "request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx",
        "code": "",
        "message": "",
        "output": {
            "text": null,
            "finish_reason": null,
            "choices": null,
            "audio": null,
            "task_id": "77093787-a217-4c29-9cd4-ca7b5ac86xxx",
            "task_status": "PENDING"
        },
        "usage": {
            "input_tokens": 0,
            "output_tokens": 0,
            "characters": 0
        }
    }
  2. タスク結果クエリのレスポンス例

    URL は 24 時間有効です。速やかに画像をダウンロードしてください。
    {
        "status_code": 200,
        "request_id": "56e318fd-ed60-99e8-8ca1-cdef25ca4xxx",
        "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"
                            },
                            {
                                "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                                "type": "image"
                            },
                            {
                                "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                                "type": "image"
                            },
                            {
                                "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                                "type": "image"
                            }
                        ]
                    }
                }
            ],
            "audio": null,
            "task_id": "77093787-a217-4c29-9cd4-ca7b5ac86xxx",
            "task_status": "SUCCEEDED",
            "submit_time": "2026-03-31 23:04:46.166",
            "scheduled_time": "2026-03-31 23:04:46.208",
            "end_time": "2026-03-31 23:05:11.664",
            "finished": true
        },
        "usage": {
            "input_tokens": 720,
            "output_tokens": 11,
            "characters": 0,
            "size": "2048*2048",
            "total_tokens": 731,
            "image_count": 4
        }
    }

Java SDK

SDK のパラメーター名は、HTTP API とほぼ一致しています。

画像生成タスクには時間がかかることがあるため、SDK は HTTP 非同期ワークフローをラップしています。同期呼び出しと非同期呼び出しの両方がサポートされています。

重要

DashScope Java SDK のバージョンが 2.22.13 以降であることを確認してください。

シンガポール

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

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

中国 (北京)

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

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

画像編集

同期呼び出し

リクエスト例
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/ja/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/20251229/pjeqdf/car.webp";
        String image2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/20251229/xsunlm/paint.webp";

        // メソッド 2:ローカルファイルを使用。絶対パスと相対パスの両方がサポートされています。
        // フォーマット:file:// + ファイルパス
        // String image1 = "file:///path/to/your/car.png";
        // String image2 = "file:///path/to/your/paint.png";

        // メソッド 3:Base64 エンコードされた画像を使用。
        // String image1 = encodeFile("/path/to/your/car.png");
        // String image2 = encodeFile("/path/to/your/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": ""
}

非同期呼び出し

リクエスト例
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/ja/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/20251229/pjeqdf/car.webp";
        String image2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/20251229/xsunlm/paint.webp";

        // [メソッド 2] ローカルファイルを使用 (絶対パスと相対パスをサポート)
        // 必須フォーマット:file:// + ファイルパス
        // String image1 = "file:///path/to/your/car.png";
        // String image2 = "file:///path/to/your/paint.png";

        // [メソッド 3] Base64 エンコードされた画像を使用
        // String image1 = encodeFile("/path/to/your/car.png");
        // String image2 = encodeFile("/path/to/your/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();
    }
}
レスポンス例
  1. タスク作成のレスポンス例

    {
        "requestId": "ccf4b2f4-bf30-9e13-9461-3a28c6a7bxxx",
        "output": {
            "task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx",
            "task_status": "PENDING"
        },
        "status_code": 200,
        "code": "",
        "message": ""
    }
  2. タスク結果クエリのレスポンス例

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

画像セット生成

同期呼び出し

リクエスト例
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/ja/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://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp";

        // メソッド 2:ローカルファイルを使用 (絶対パスと相対パスの両方をサポート)
        // フォーマット:file:// + ファイルパス
        // String image1 = "file:///path/to/your/image.png";

        // メソッド 3:Base64 エンコードされた画像を使用
        // String image1 = encodeFile("/path/to/your/image.png");

        // テキスト入力メッセージを構築します。これは、テキストから画像へのシリーズ生成と画像から画像へのシリーズ生成の両方をサポートします。この例では、テキストから画像へのシリーズ生成を示します。
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Collections.singletonList(
                        Collections.singletonMap("text", "同じ野良の茶トラ猫を記録した映画のような画像シリーズ。その特徴は一貫している必要があります。最初の画像:春、猫は満開の桜の木の間を縫うように歩きます。2番目の画像:夏、猫は古い通りの木陰で涼んでいます。3番目の画像:秋、猫は金色の落ち葉の絨毯の上を歩きます。4番目の画像:冬、猫は雪に足跡を残します。")
                )).build();
        // 画像から画像へのシリーズ生成の場合、以下のコードのコメントを解除し、上のプレーンテキストメッセージビルダーをコメントアウトします。
        // ImageGenerationMessage message = ImageGenerationMessage.builder()
        //         .role("user")
        //         .content(Arrays.asList(
        //                 Collections.singletonMap("text", "参照画像のスタイルに基づいて四季の画像シリーズを生成します。"),
        //                 Collections.singletonMap("image", image1)
        //         )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.7-image-pro")
                .messages(Collections.singletonList(message))
                .enableSequential(true)
                .n(4)
                .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": "4678c314-b37a-91c9-a2ae-2d3cd54bbxxx",
    "usage": {
        "input_tokens": 720,
        "output_tokens": 11,
        "total_tokens": 731,
        "image_count": 4,
        "size": "2048*2048"
    },
    "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"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "finished": true
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

非同期呼び出し

リクエスト例
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/ja/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 ImageGenerationResult waitTask(String taskId)
            throws ApiException, NoApiKeyException {
        ImageGeneration imageGeneration = new ImageGeneration();
        return imageGeneration.wait(taskId, apiKey);
    }

    public static void asyncCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
        /*
         * 画像入力メソッドの説明 (画像から画像へのセット生成シナリオ用):
         * 以下の 3 つの画像入力メソッドが提供されています。いずれか 1 つを選択できます。
         * 1. パブリック URL を使用 - パブリックにアクセス可能な画像に適しています。
         * 2. ローカルファイルを使用 - ローカルでの開発およびテストに適しています。
         * 3. Base64 エンコーディングを使用 - 非公開の画像や暗号化された伝送が必要なシナリオに適しています。
         */
        // [メソッド 1] パブリック画像 URL を使用
        // String image1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp";

        // [メソッド 2] ローカルファイルを使用 (絶対パスと相対パスをサポート)
        // フォーマット:file:// + ファイルパス
        // String image1 = "file:///path/to/your/image.png";

        // [メソッド 3] Base64 エンコードされた画像を使用
        // String image1 = encodeFile("/path/to/your/image.png");

        // テキスト入力メッセージを構築します (テキストから画像へのセット生成と画像から画像へのセット生成の両方をサポートします。この例ではテキストから画像へのセット生成を使用します)。
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Collections.singletonList(
                        Collections.singletonMap("text", "同じ野良の茶トラ猫を記録した映画のような画像セット。その特徴はすべての画像で一貫している必要があります。画像 1:春、茶トラ猫は満開の桜の木の間を縫うように歩きます。画像 2:夏、茶トラ猫は古い通りの木陰で涼んでいます。画像 3:秋、茶トラ猫は金色の落ち葉の絨毯の上を歩きます。画像 4:冬、茶トラ猫は雪の上を歩きながら足跡を残します。")
                )).build();
        // 画像から画像へのセット生成シナリオの場合:以下のコードのコメントを解除し、上のプレーンテキスト構築をコメントアウトします。
        // ImageGenerationMessage message = ImageGenerationMessage.builder()
        //         .role("user")
        //         .content(Arrays.asList(
        //                 Collections.singletonMap("text", "参照画像のスタイルに基づいて四季の画像セットを生成します。"),
        //                 Collections.singletonMap("image", image1)
        //         )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.7-image-pro")
                .messages(Collections.singletonList(message))
                .enableSequential(true)
                .n(4)
                .size("2K") // wan2.7-image-pro モデルは、テキストからの画像生成のみ 4K 解像度をサポートします。画像編集と画像セット生成は最大 2K 解像度までサポートします。
                .build();

        ImageGeneration imageGeneration = new ImageGeneration();
        ImageGenerationResult taskResult = null;
        try {
            System.out.println("----非同期呼び出し、タスク作成中----");
            taskResult = imageGeneration.asyncCall(param);
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            throw new RuntimeException(e.getMessage());
        }
        System.out.println("タスク作成: " + JsonUtils.toJson(taskResult));

        // タスクの完了を待ちます。
        String taskId = taskResult.getOutput().getTaskId();
        ImageGenerationResult result = waitTask(taskId);
        // 結果の画像 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();
    }
}
レスポンス例
  1. タスク作成のレスポンス例

    {
        "requestId": "7d026dc1-e8c9-9caa-84ac-e82e2da97xxx",
        "output": {
            "task_id": "2de18c56-c151-4b80-8105-1d164733exxx",
            "task_status": "PENDING"
        },
        "status_code": 200,
        "code": "",
        "message": ""
    }
  2. タスク結果クエリのレスポンス例

    URL は 24 時間有効です。速やかに保存してください。
    {
        "requestId": "daea7295-4ce0-928a-9a11-4d2bea058xxx",
        "usage": {
            "input_tokens": 720,
            "output_tokens": 11,
            "total_tokens": 731,
            "image_count": 4,
            "size": "2048*2048"
        },
        "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"
                            },
                            {
                                "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                                "type": "image"
                            },
                            {
                                "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                                "type": "image"
                            },
                            {
                                "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                                "type": "image"
                            }
                        ]
                    }
                }
            ],
            "task_id": "2de18c56-c151-4b80-8105-1d164733exxx",
            "task_status": "SUCCEEDED",
            "finished": true,
            "submit_time": "2026-03-31 19:49:53.124",
            "scheduled_time": "2026-03-31 19:49:53.175",
            "end_time": "2026-03-31 19:50:53.160"
        },
        "status_code": 200,
        "code": "",
        "message": ""
    }

課金とレート制限

  • モデルの無料クォータと単価については、モデルの価格設定をご参照ください。

  • モデルのレート制限については、Wanxiangをご参照ください。

  • 課金の詳細:正常に生成された画像の数に基づいて課金されます。失敗した呼び出しや処理エラーは、料金が発生したり、新規ユーザー向けの無料クォータを消費したりすることはありません。

エラーコード

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