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 解像度までサポートします。
画像編集
インタラクティブな編集
画像セット生成
|
ヘッダー |
|
|
Content-Type リクエストのコンテンツタイプとして |
|
|
Authorization Model Studio API キーでリクエストを認証します。例:Bearer sk-xxxx。 |
|
リクエストボディ |
|
|
model モデル名。有効な値: |
|
|
input 入力オブジェクト。 |
|
|
parameters モデルのパラメーター設定。 |
レスポンスパラメーター |
タスクの正常な実行タスクデータ (タスクステータスと画像 URL) は 24 時間のみ保持され、その後自動的にパージされます。生成された画像は速やかに保存してください。
タスクの異常な実行タスクが失敗した場合、レスポンスの
|
|
output タスクの出力情報。 |
|
|
usage リクエストの使用統計。成功した結果のみがカウントされます。 |
|
|
request_id トレースとトラブルシューティングのための一意のリクエスト識別子。 |
|
|
code エラーコード。失敗したリクエストに対してのみ返されます。エラーコードをご参照ください。 |
|
|
message 詳細なエラーメッセージ。失敗したリクエストに対してのみ返されます。エラーコードをご参照ください。 |
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 解像度までサポートします。
画像編集
インタラクティブな編集
画像セット生成wan2.7-image-pro モデルは、画像セット生成で最大 2K 解像度をサポートします。
|
ヘッダー |
|
|
Content-Type リクエストのコンテンツタイプは、 |
|
|
Authorization Model Studio API キーでリクエストを認証します。例:Bearer sk-xxxx。 |
|
|
X-DashScope-Async 非同期処理を有効にします。HTTP リクエストは、非同期呼び出しのみをサポートします。 重要
このリクエストヘッダーがない場合、「current user api does not support synchronous calls」というエラーが返されます。 |
|
リクエストボディ |
|
|
model モデル名。有効な値: |
|
|
input 入力オブジェクト。 |
|
|
parameters モデルのパラメーター設定。 |
レスポンスパラメーター |
成功したレスポンス
エラーレスポンスタスクの作成に失敗しました。エラーコードをご参照ください。
|
|
output タスクの出力情報。 |
|
|
request_id トレースとトラブルシューティングのための一意のリクエスト識別子。 |
|
|
code エラーコード。失敗したリクエストに対してのみ返されます。エラーコードをご参照ください。 |
|
|
message 詳細なエラーメッセージ。失敗したリクエストに対してのみ返されます。エラーコードをご参照ください。 |
ステップ 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}
リクエストパラメーター |
タスク結果のクエリ
|
ヘッダー |
|
|
Authorization Model Studio API キーでリクエストを認証します。例:Bearer sk-xxxx。 |
|
パスパラメーター |
|
|
task_id タスクの ID。 |
レスポンスパラメーター |
タスクの正常な実行タスクデータ (タスクステータスと画像 URL) は 24 時間のみ保持され、その後自動的にパージされます。生成された画像は速やかに保存してください。
タスクの異常な実行タスクが失敗した場合、レスポンスの
|
|
output タスクの出力情報。 |
|
|
usage リクエストの使用統計。成功した結果のみがカウントされます。 |
|
|
request_id トレースとトラブルシューティングのための一意のリクエスト識別子。 |
|
|
code エラーコード。失敗したリクエストに対してのみ返されます。エラーコードをご参照ください。 |
|
|
message 詳細なエラーメッセージ。失敗したリクエストに対してのみ返されます。エラーコードをご参照ください。 |
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)
レスポンス例
-
タスク作成のレスポンス例
{ "status_code": 200, "request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx", "code": "", "message": "", "output": { "text": null, "finish_reason": null, "choices": null, "audio": null, "task_id": "127ec645-118f-4884-955d-0eba8dxxxxxx", "task_status": "PENDING" }, "usage": { "input_tokens": 0, "output_tokens": 0, "characters": 0 } } -
タスク結果クエリのレスポンス例
URL は 24 時間有効です。速やかに画像をダウンロードしてください。
{ "status_code": 200, "request_id": "3b99aae5-d26f-9059-8dd0-ee9ca4804xxx", "code": null, "message": "", "output": { "text": null, "finish_reason": null, "choices": [ { "finish_reason": "stop", "message": { "role": "assistant", "content": [ { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" } ] } } ], "audio": null, "task_id": "127ec645-118f-4884-955d-0eba8dxxxxxx", "task_status": "SUCCEEDED", "submit_time": "2026-03-31 22:58:47.646", "scheduled_time": "2026-03-31 22:58:47.683", "end_time": "2026-03-31 22:58:59.642", "finished": true }, "usage": { "input_tokens": 18711, "output_tokens": 2, "characters": 0, "size": "2985*1405", "total_tokens": 18713, "image_count": 1 } }
画像セット生成
同期呼び出し
リクエスト例
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}")
レスポンス例
-
タスク作成のレスポンス例
{ "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 } } -
タスク結果クエリのレスポンス例
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();
}
}
レスポンス例
-
タスク作成のレスポンス例
{ "requestId": "ccf4b2f4-bf30-9e13-9461-3a28c6a7bxxx", "output": { "task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx", "task_status": "PENDING" }, "status_code": 200, "code": "", "message": "" } -
タスク結果クエリのレスポンス例
URL は 24 時間有効です。速やかに保存してください。
{ "requestId": "60a08540-f1c1-9e76-8cd3-d5949db8cxxx", "usage": { "input_tokens": 18711, "output_tokens": 2, "total_tokens": 18713, "image_count": 1, "size": "2985*1405" }, "output": { "choices": [ { "finish_reason": "stop", "message": { "role": "assistant", "content": [ { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" } ] } } ], "task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx", "task_status": "SUCCEEDED", "finished": true, "submit_time": "2026-03-31 19:57:58.840", "scheduled_time": "2026-03-31 19:57:58.877", "end_time": "2026-03-31 19:58:11.563" }, "status_code": 200, "code": "", "message": "" }
画像セット生成
同期呼び出し
リクエスト例
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();
}
}
レスポンス例
-
タスク作成のレスポンス例
{ "requestId": "7d026dc1-e8c9-9caa-84ac-e82e2da97xxx", "output": { "task_id": "2de18c56-c151-4b80-8105-1d164733exxx", "task_status": "PENDING" }, "status_code": 200, "code": "", "message": "" } -
タスク結果クエリのレスポンス例
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をご参照ください。
-
課金の詳細:正常に生成された画像の数に基づいて課金されます。失敗した呼び出しや処理エラーは、料金が発生したり、新規ユーザー向けの無料クォータを消費したりすることはありません。
エラーコード
モデルの呼び出しが失敗し、エラーメッセージが返された場合は、エラーコードで解決策をご確認ください。