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

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

最終更新日:Jun 30, 2026

Wan2.7-Image は、Text-to-Image、Text-to-Image セット、Image-to-Image セット、画像編集、および複数画像の参照生成をサポートします。

モデルの概要

モデル

説明

出力画像の仕様

wan2.7-image-pro

Wan 2.7 画像 Pro。Text-to-Image (画像セットではない) での 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 に置き換えてください。

リクエストパラメーター

Text-to-Image

wan2.7-image-pro モデルは、Text-to-Image でのみ 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": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display"}
                    ]
                }
            ]
        },
        "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/zh-CN/20251229/pjeqdf/car.webp"},
                        {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"},
                        {"text": "Spray-paint the graffiti from image 2 onto the car in image 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": "Place the alarm clock from image 1 into the bounding box of image 2, and blend the scene and lighting naturally."}
                    ]
                }
            ]
        },
        "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": "A cinematic group of images documenting the same stray ginger cat. The features must be consistent throughout. First image: In spring, the ginger cat weaves through blooming cherry blossom trees. Second image: In summer, the ginger cat cools off in the shade on an old street. Third image: In autumn, the ginger cat steps on a ground covered with golden fallen leaves. Fourth image: In winter, the ginger cat walks on the snow, leaving footprints."}
                    ]
                }
            ]
        },
        "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 枚の画像を入力できます。

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

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

  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 の仕様をサポートします。

    • 適用範囲

      • Text-to-Image (画像入力なし、画像セット生成ではない):1K、2K、4K をサポートします。

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

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

    • 画像のアスペクト比

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

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

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

    • Text-to-Image:総ピクセル数は 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%")。すべての ratio 値の合計は 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 に置き換えてください。

リクエストパラメーター

Text-to-Image

wan2.7-image-pro モデルは、Text-to-Image でのみ 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": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display"}
                    ]
                }
            ]
        },
        "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": "Spray-paint the graffiti from image 2 onto the car in image 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": "Place the alarm clock from image 1 into the selected area of image 2, and blend the scene and lighting naturally."}
                    ]
                }
            ]
        },
        "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": "A cinematic photo set featuring the same stray orange cat, whose features must remain consistent across all images. First image: In spring, the cat weaves through blooming cherry blossom trees. Second image: In summer, the cat cools off in the shade on an old street. Third image: In autumn, the cat steps on a ground covered in golden fallen leaves. Fourth image: In winter, the cat walks on the snow, leaving footprints."}
                    ]
                }
            ]
        },
        "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 枚の画像を入力できます。

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

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

  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 の仕様をサポートします。

    • 適用範囲

      • Text-to-Image (画像入力なし、画像セット生成ではない):1K、2K、4K をサポートします。

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

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

    • 画像のアスペクト比

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

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

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

    • Text-to-Image:総ピクセル数は 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%" など) まで指定する必要があります。すべての ratio 値の合計は 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+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 です。

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 です。base_url はリージョンによって異なります。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください:api_key="sk-xxx"
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Base64 エンコーディング関数 ---
# Base64 エンコーディング形式は data:{MIME_type};base64,{base64_data} です
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("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}"

"""
画像入力メソッド:
以下に 3 つの画像入力メソッドを示します。いずれか 1 つを選択してください。
1. パブリック URL を使用:このメソッドは、パブリックにアクセス可能な画像に適しています。
2. ローカルファイルを使用:このメソッドは、ローカルでの開発およびテストに適しています。
3. Base64 エンコーディングを使用:このメソッドは、非公開の画像や暗号化された伝送が必要なシナリオに適しています。
"""
# [メソッド 1] パブリック画像 URL を使用
image_1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"
image_2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"

# [メソッド 2] ローカルファイルを使用 (絶対パスと相対パスをサポート)
# image_1 = "file:///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": "Spray the graffiti from image 2 onto the car in image 1"},
        {"image": image_1},
        {"image": image_2},
    ],
)
print("----sync call, please wait a moment----")
rsp = ImageGeneration.call(
    model="wan2.7-image-pro",
    api_key=api_key,
    messages=[message],
    watermark=False,
    n=1,
    size="2K",  # wan2.7-image-pro は、Text-to-Image でのみ 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"Image saved to {file_name}")
else:
    print(f"Failed: 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 です。base_url はリージョンによって異なります。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください:api_key="sk-xxx"
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Base64 エンコーディング関数 ---
# Base64 エンコーディング形式は data:{MIME_type};base64,{base64_data} です
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("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}"

"""
画像入力メソッド:
以下に 3 つの画像入力メソッドを示します。いずれか 1 つを選択してください。
1. パブリック URL を使用 - パブリックにアクセス可能な画像に適しています。
2. ローカルファイルを使用 - ローカルでの開発およびテストに適しています。
3. Base64 エンコーディングを使用 - 非公開の画像や暗号化された伝送が必要なシナリオに適しています。
"""
# [メソッド 1] パブリック画像 URL を使用
image_1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"
image_2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"

# [メソッド 2] ローカルファイルを使用 (絶対パスと相対パスをサポート)
# image_1 = "file:///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("Creating async task...")
    message = Message(
        role="user",
        content=[
            {"text": "Spray the graffiti from image 2 onto the car in image 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 は、Text-to-Image シナリオでのみ 4K 解像度をサポートします。画像編集とコラージュ生成は最大 2K 解像度までサポートします。
    )

    if response.status_code == 200:
        print("Task created successfully:", response)
        return response
    else:
        raise Exception(f"Failed to create task: {response.code} - {response.message}")

# タスクの完了を待ちます。
def wait_for_completion(task_response):
    print("Waiting for task completion...")
    status = ImageGeneration.wait(task=task_response, api_key=api_key)

    if status.output.task_status == "SUCCEEDED":
        print("Task succeeded!")
        # 結果の画像 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"Image saved to {file_name}")
    else:
        raise Exception(f"Task failed with status: {status.output.task_status}")

# 非同期タスクに関する情報を取得します。
def fetch_task_status(task):
    print("Fetching task status...")
    status = ImageGeneration.fetch(task=task, api_key=api_key)

    if status.status_code == HTTPStatus.OK:
        print("Task status:", status.output.task_status)
        print("Response details:", status)
    else:
        print(f"Failed to fetch status: {status.code} - {status.message}")

# 非同期タスクをキャンセルします。
def cancel_task(task):
    print("Canceling task...")
    response = ImageGeneration.cancel(task=task, api_key=api_key)

    if response.status_code == HTTPStatus.OK:
        print("Task canceled successfully:", response.output.task_status)
    else:
        print(f"Failed to cancel task: {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 です。base_url はリージョンによって異なります。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください:api_key="sk-xxx"
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください。
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Base64 エンコード関数 ---
# Base64 エンコード形式は data:{MIME_type};base64,{base64_data} です。
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("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}"

"""
画像入力メソッドの説明 (画像から画像へのシーケンス生成用):
以下の 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": "A cinematic image sequence featuring the same stray orange cat, whose features must be consistent across all images. First image: In spring, the orange cat weaves through blooming cherry blossom trees. Second image: In summer, the orange cat cools off in the shade of a tree on an old street. Third image: In autumn, the orange cat walks on a carpet of golden fallen leaves. Fourth image: In winter, the orange cat leaves footprints as it walks on the snow."
        }
        # 画像から画像へのシーケンス生成の場合:次の行のコメントを解除し、上記のプレーンテキストをコメントアウトします。
        # {"text": "Generate a four-seasons image sequence based on the style of the reference image"},
        # {"image": image_1}
    ],
)

print("----sync call, please wait a moment----")
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 は、Text-to-Image シナリオでのみ 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"Image saved to {file_name}")
else:
    print(f"Failed: 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 です。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/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("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}"

"""
画像入力メソッドの説明 (画像から画像へのシーケンス生成用):
以下に 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": "A cinematic sequence of images documenting the same stray orange cat, whose features must remain consistent across all images. Image 1: In spring, the cat weaves through blooming cherry blossom trees. Image 2: In summer, the cat cools off in the shade of trees on an old street. Image 3: In autumn, the cat steps on a carpet of golden fallen leaves. Image 4: In winter, the cat walks on the snow, leaving footprints."
            }
            # 画像から画像へのシーケンス生成シナリオ:次の行のコメントを解除し、上記のプレーンテキストをコメントアウトします。
            # {"text": "Generate a sequence of four seasonal images based on the style of the reference image."},
            # {"image": image_1}
        ],
    )

    # 非同期タスクを送信
    print("Submitting an asynchronous task...")
    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 は、Text-to-Image シナリオでのみ 4K 解像度をサポートします。画像編集および画像シーケンス生成では、最大 2K の解像度をサポートします。
    )

    if response.status_code == 200:
        print(f"Task submitted successfully. Task ID: {response.output.task_id}")

        # タスクの完了を待機
        status = ImageGeneration.wait(task=response, api_key=api_key)

        if status.output.task_status == "SUCCEEDED":
            print("Task completed!")
            # 結果の画像 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"Image saved to {file_name}")
        else:
            print(f"Task failed. Status: {status.output.task_status}")
    else:
        print(f"Failed to create the task: {response.code} - {response.message}")

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"Error: {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 です。base_url はリージョンによって異なります。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください: apiKey="sk-xxx"
    // API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key にアクセスしてください
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64 エンコーディング関数 ---
    // Base64 エンコーディング形式: data:{MIME_type};base64,{base64_data}
    public static String encodeFile(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(Paths.get(filePath));
        return "data:" + mimeType + ";base64," + base64String;
    }

    public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
        /*
         * 画像入力メソッドの説明:
         * 以下に 3 つの画像入力メソッドを示します。いずれか 1 つを選択してください。
         * 1. パブリック URL を使用: 一般公開されている画像に適しています。
         * 2. ローカルファイルを使用: ローカルでの開発とテストに適しています。
         * 3. Base64 エンコーディングを使用: 非公開の画像や暗号化された伝送が必要なシナリオに適しています。
         */
        // メソッド 1: パブリック画像の URL を使用します。
        String image1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp";
        String image2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp";

        // メソッド 2: ローカルファイルを使用します。絶対パスと相対パスの両方がサポートされています。
        // 形式: file:// + ファイルパス
        // String image1 = "file:///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 です。base_url はリージョンによって異なります。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください: apiKey="sk-xxx"
    // API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key にアクセスしてください
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64 エンコーディング関数 ---
    // Base64 エンコーディング形式は data:{MIME_type};base64,{base64_data} です
    public static String encodeFile(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(Paths.get(filePath));
        return "data:" + mimeType + ";base64," + base64String;
    }

    public static void asyncCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
        /*
         * 画像入力メソッドの説明:
         * 以下に 3 つの画像入力メソッドを示します。いずれか 1 つを選択できます。
         * 1. パブリック URL を使用 - 一般公開されている画像に適しています。
         * 2. ローカルファイルを使用 - ローカルでの開発とテストに適しています。
         * 3. Base64 エンコーディングを使用 - 非公開の画像を含むシナリオや、暗号化された伝送が必要なシナリオに適しています。
         */
        // [メソッド 1] パブリック画像の URL を使用
        String image1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp";
        String image2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp";

        // [メソッド 2] ローカルファイルを使用 (絶対パスと相対パスをサポート)
        // 必要な形式: file:// + ファイルパス
        // String image1 = "file:///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 はシンガポールリージョン用です。base_url はリージョンによって異なります。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 環境変数を設定していない場合は、次の行をご自身の Model Studio API キーに置き換えてください:apiKey="sk-xxx"
    // API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください。
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64 エンコーディング関数 ---
    // Base64 エンコーディングのフォーマットは data:{MIME_type};base64,{base64_data} です
    public static String encodeFile(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(Paths.get(filePath));
        return "data:" + mimeType + ";base64," + base64String;
    }

    public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
        /*
         * 画像の入力方法 (Image-to-Image 画像セット生成向け):
         * 画像入力には以下の 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");

        // テキスト入力メッセージを構築します。これは Text-to-Image と Image-to-Image の両方の画像セット生成をサポートします。この例では、Text-to-Image 画像セット生成をデモンストレーションします。
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Collections.singletonList(
                        Collections.singletonMap("text", "同じ野良の茶トラ猫を記録した映画のような一連の画像。その特徴は一貫している必要があります。1枚目の画像:春、満開の桜の木々の間を歩く猫。2枚目の画像:夏、古い町並みの木陰で涼む猫。3枚目の画像:秋、黄金色の落ち葉の絨毯の上を歩く猫。4枚目の画像:冬、雪の中に足跡を残す猫。")
                )).build();
        // Image-to-Image 画像セット生成の場合は、次のコードのコメントアウトを解除し、上記のプレーンテキストメッセージビルダーをコメントアウトします。
        // 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 モデルは、Text-to-Image 生成でのみ 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 はシンガポールリージョン用です。base_url はリージョンによって異なります。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 環境変数を設定していない場合は、次の行をご自身の Model Studio API キーに置き換えてください:apiKey="sk-xxx"
    // API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください。
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64 エンコーディング関数 ---
    // Base64 エンコーディングのフォーマットは data:{MIME_type};base64,{base64_data} です
    public static String encodeFile(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(Paths.get(filePath));
        return "data:" + mimeType + ";base64," + base64String;
    }

    public static 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 {
        /*
         * 画像入力方法の説明 (Image-to-Image 画像セット生成シナリオ向け):
         * 画像入力には以下の 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");

        // テキスト入力メッセージを構築します (Text-to-Image 画像セットと Image-to-Image 画像セットの両方の生成をサポートします。この例では Text-to-Image 画像セット生成を使用します)。
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Collections.singletonList(
                        Collections.singletonMap("text", "同じ野良の茶トラ猫を記録した映画のような一連の画像。その特徴はすべての画像で一貫している必要があります。画像1:春、満開の桜の木々の間を歩く茶トラ猫。画像2:夏、古い町並みの木陰で涼む茶トラ猫。画像3:秋、黄金色の落ち葉の絨毯の上を歩く茶トラ猫。画像4:冬、雪の上を歩きながら足跡を残す茶トラ猫。")
                )).build();
        // Image-to-Image 画像セット生成シナリオの場合:次のコードのコメントアウトを解除し、上記のプレーンテキストを作成する部分をコメントアウトします。
        // 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 モデルは、Text-to-Image 生成でのみ 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」をご参照ください。

  • 課金の詳細:正常に生成されたイメージ数に基づいて課金されます。呼び出しの失敗や処理エラーが発生した場合、料金は発生せず、新規ユーザー向けの無料クォータも消費されません。

エラーコード

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