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-Imagewan2.7-image-pro モデルは、Text-to-Image でのみ 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 に置き換えてください。
リクエストパラメーター |
Text-to-Imagewan2.7-image-pro モデルは、Text-to-Image でのみ 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 です。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)
レスポンス例
-
タスク作成のレスポンス例
{ "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 です。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}")
応答例
-
タスク作成の応答例
{ "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 です。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();
}
}
レスポンス例
-
タスク作成のリクエストに対するレスポンス例
{ "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 はシンガポールリージョン用です。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();
}
}
レスポンス例
-
タスク作成のレスポンス例
{ "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」をご参照ください。
-
課金の詳細:正常に生成されたイメージ数に基づいて課金されます。呼び出しの失敗や処理エラーが発生した場合、料金は発生せず、新規ユーザー向けの無料クォータも消費されません。
エラーコード
モデルの呼び出しが失敗し、エラーメッセージが返された場合は、エラーコードをご参照ください。