萬相2.7映像產生與編輯模型支援文生圖、文生組圖、圖生組圖、影像編輯和多圖參考產生。
模型概覽
|
模型名稱 |
模型簡介 |
輸出映像規格 |
|
wan2.7-image-pro |
萬相2.7 image專業版,文生圖(非組圖產生)支援4K高清輸出 |
圖片格式:PNG。 映像解析度和尺寸請參見size參數。 |
|
wan2.7-image |
萬相2.7 image,產生速度更快 |
調用前,請查閱各地區支援的模型列表與價格。
前提條件
您需要已擷取API Key並配置API Key到環境變數。請將範例程式碼中的 DASHSCOPE_API_HOST 替換為擷取的 API Host。
華北2(北京)和新加坡地區擁有獨立的 API Key 與請求地址,不可混用,跨地區調用將導致鑒權失敗或服務報錯。
阿里雲百鍊為華北2(北京)、新加坡地區推出了業務空間專屬網域名稱,能夠為推理請求提供卓越的效能和更高的穩定性,建議遷移至新網域名稱:
-
華北2(北京)地區:從
https://dashscope.aliyuncs.com遷移至https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com -
新加坡地區:從
https://dashscope-intl.aliyuncs.com遷移至https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
其中 {WorkspaceId} 為您的業務空間 ID,可在阿里雲百鍊控制台的業務空間詳情頁面查看。現有網域名稱仍可正常使用。
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解析度
影像編輯
互動式編輯
組圖產生wan2.7-image-pro組圖產生僅支援最高2K解析度。
|
要求標頭(Headers) |
|
|
Content-Type 請求內容類型。此參數必須設定為 |
|
|
Authorization 請求身份認證。介面使用阿里雲百鍊API Key進行身份認證。樣本值:Bearer sk-xxxx。 |
|
請求體(Request Body) |
|
|
model 模型名稱。可選值: |
|
|
input 輸入的基本資料。 |
|
|
parameters 模型參數配置。 |
響應參數 |
任務執行成功任務資料(如任務狀態、映像URL等)僅保留24小時,逾時後會被自動清除。請您務必及時儲存產生的映像。
任務執行異常如果因為某種原因導致任務執行失敗,將返回相關資訊,可以通過code和message欄位明確指示錯誤原因。請參見錯誤碼進行解決。
|
|
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解析度。
|
要求標頭(Headers) |
|
|
Content-Type 請求內容類型。此參數必須設定為 |
|
|
Authorization 請求身份認證。介面使用阿里雲百鍊API Key進行身份認證。樣本值:Bearer sk-xxxx。 |
|
|
X-DashScope-Async 非同步處理配置參數。HTTP請求只支援非同步,必須設定為 重要
缺少此要求標頭將報錯:“current user api does not support synchronous calls”。 |
|
請求體(Request Body) |
|
|
model 模型名稱。可選值: |
|
|
input 輸入的基本資料。 |
|
|
parameters 模型參數配置。 |
響應參數 |
成功響應請儲存 task_id,用於查詢任務狀態與結果。
異常響應建立任務失敗,請參見錯誤碼進行解決。
|
|
output 任務輸出資訊。 |
|
|
request_id 請求唯一標識。可用於請求明細溯源和問題排查。 |
|
|
code 請求失敗的錯誤碼。請求成功時不會返回此參數,詳情請參見錯誤碼。 |
|
|
message 請求失敗的詳細資料。請求成功時不會返回此參數,詳情請參見錯誤碼。 |
步驟2:根據任務ID查詢結果
新加坡
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
北京
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
請求參數 |
查詢任務結果將 |
要求標頭(Headers) |
|
|
Authorization 請求身份認證。介面使用阿里雲百鍊API Key進行身份認證。樣本值:Bearer sk-xxxx。 |
|
URL路徑參數(Path parameters) |
|
|
task_id 任務ID。 |
響應參數 |
任務執行成功任務資料(如任務狀態、映像URL等)僅保留24小時,逾時後會被自動清除。請您務必及時儲存產生的映像。
任務執行異常如果因為某種原因導致任務執行失敗,將返回相關資訊,可以通過code和message欄位明確指示錯誤原因。請參見錯誤碼進行解決。
|
|
output 任務輸出資訊。 |
|
|
usage 輸出資訊統計。只對成功的結果計數。 |
|
|
request_id 請求唯一標識。可用於請求明細溯源和問題排查。 |
|
|
code 請求失敗的錯誤碼。請求成功時不會返回此參數,詳情請參見錯誤碼。 |
|
|
message 請求失敗的詳細資料。請求成功時不會返回此參數,詳情請參見錯誤碼。 |
Python SDK調用
SDK 參數命名與HTTP介面基本一致。
任務可能耗時較長,SDK 已封裝HTTP非同步呼叫流程,同時支援同步和非同步呼叫。
具體耗時受限於排隊任務數和服務執行情況,請在擷取結果時耐心等待。
請確保 DashScope Python SDK版本不低於 1.25.15,再運行以下代碼。更新請參考安裝SDK。
各地區的base_url和API Key 不通用,以下樣本以新加坡地區為例進行調用:
新加坡
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
調用時請將{WorkspaceId}替換為真實的Workspace ID。
華北2(北京)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
調用時請將{WorkspaceId}替換為真實的Workspace 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
# 以下為新加坡地區的URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
# 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/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}"
"""
映像輸入方式說明:
以下提供了三種圖片輸入方式,三選一即可
1. 使用公網URL - 適合已有公開可訪問的圖片
2. 使用本地檔案 - 適合本地開發測試
3. 使用Base64編碼 - 適合私人圖片或需要加密傳輸的情境
"""
# 【方式一】使用公網圖片 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"
# 【方式二】使用本地檔案(支援絕對路徑和相對路徑)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"
# 【方式三】使用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("----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僅文生圖情境支援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
# 以下為新加坡地區的URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
# 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/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}"
"""
映像輸入方式說明:
以下提供了三種圖片輸入方式,三選一即可
1. 使用公網URL - 適合已有公開可訪問的圖片
2. 使用本地檔案 - 適合本地開發測試
3. 使用Base64編碼 - 適合私人圖片或需要加密傳輸的情境
"""
# 【方式一】使用公網圖片 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"
# 【方式二】使用本地檔案(支援絕對路徑和相對路徑)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"
# 【方式三】使用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": "把圖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("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
# 以下為新加坡地區的URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
# 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/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}"
"""
映像輸入方式說明(圖生組圖情境):
以下提供了三種圖片輸入方式,三選一即可
1. 使用公網URL - 適合已有公開可訪問的圖片
2. 使用本地檔案 - 適合本地開發測試
3. 使用Base64編碼 - 適合私人圖片或需要加密傳輸的情境
"""
# 【方式一】使用公網圖片 URL
# image_1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp"
# 【方式二】使用本地檔案(支援絕對路徑和相對路徑)
# image_1 = "file:///path/to/your/image.png"
# 【方式三】使用Base64編碼的圖片
# image_1 = encode_file("/path/to/your/image.png")
message = Message(
role="user",
content=[
{
"text": "電影感組圖,記錄同一隻流浪橘貓,特徵必須前後一致。第一張:春天,橘貓穿梭在盛開的櫻花樹下;第二張:夏天,橘貓在老街的樹蔭下乘涼避暑;第三張:秋天,橘貓踩在滿地的金色落葉上;第四張:冬天,橘貓在雪地上走留下足跡。"
}
# 圖生組圖情境:取消以下注釋並注釋掉上方純文字
# {"text": "參考圖片風格產生四季組圖"},
# {"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僅文生圖情境支援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
# 以下為新加坡地區的URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
# 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/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}"
"""
映像輸入方式說明(圖生組圖情境):
以下提供了三種圖片輸入方式,三選一即可
1. 使用公網URL - 適合已有公開可訪問的圖片
2. 使用本地檔案 - 適合本地開發測試
3. 使用Base64編碼 - 適合私人圖片或需要加密傳輸的情境
"""
# 【方式一】使用公網圖片 URL
# image_1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp"
# 【方式二】使用本地檔案(支援絕對路徑和相對路徑)
# image_1 = "file:///path/to/your/image.png"
# 【方式三】使用Base64編碼的圖片
# image_1 = encode_file("/path/to/your/image.png")
def main():
message = Message(
role="user",
content=[
{
"text": "電影感組圖,記錄同一隻流浪橘貓,特徵必須前後一致。第一張:春天,橘貓穿梭在盛開的櫻花樹下;第二張:夏天,橘貓在老街的樹蔭下乘涼避暑;第三張:秋天,橘貓踩在滿地的金色落葉上;第四張:冬天,橘貓在雪地上走留下足跡。"
}
# 圖生組圖情境:取消以下注釋並注釋掉上方純文字
# {"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"Image saved to {file_name}")
else:
print(f"任務失敗,狀態: {status.output.task_status}")
else:
print(f"任務建立失敗: {response.code} - {response.message}")
if __name__ == "__main__":
try:
main()
except Exception as e:
print(f"錯誤: {e}")
響應樣本
1、建立任務的響應樣本
{
"status_code": 200,
"request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx",
"code": "",
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": null,
"audio": null,
"task_id": "77093787-a217-4c29-9cd4-ca7b5ac86xxx",
"task_status": "PENDING"
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"characters": 0
}
}
2、查詢任務結果的響應樣本
URL 有效期間24小時,請及時下載映像。
{
"status_code": 200,
"request_id": "56e318fd-ed60-99e8-8ca1-cdef25ca4xxx",
"code": "",
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
},
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
},
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
},
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
}
]
}
}
],
"audio": null,
"task_id": "77093787-a217-4c29-9cd4-ca7b5ac86xxx",
"task_status": "SUCCEEDED",
"submit_time": "2026-03-31 23:04:46.166",
"scheduled_time": "2026-03-31 23:04:46.208",
"end_time": "2026-03-31 23:05:11.664",
"finished": true
},
"usage": {
"input_tokens": 720,
"output_tokens": 11,
"characters": 0,
"size": "2048*2048",
"total_tokens": 731,
"image_count": 4
}
}
Java SDK調用
SDK 參數命名與HTTP介面基本一致。
任務可能耗時較長,SDK 已封裝HTTP非同步呼叫流程,同時支援同步和非同步呼叫。
請確保 DashScope Java SDK版本不低於 2.22.13,否則可能不支援本文所用的部分參數。
新加坡
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
調用時請將{WorkspaceId}替換為真實的Workspace ID。
華北2(北京)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
調用時請將{WorkspaceId}替換為真實的Workspace 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}替換為真實的業務空間ID,各地區的URL不同。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey="sk-xxx"
// 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/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 {
/*
* 映像輸入方式說明:
* 以下提供了三種圖片輸入方式,三選一即可
* 1. 使用公網URL - 適合已有公開可訪問的圖片
* 2. 使用本地檔案 - 適合本地開發測試
* 3. 使用Base64編碼 - 適合私人圖片或需要加密傳輸的情境
*/
// 【方式一】使用公網圖片 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";
// 【方式二】使用本地檔案(支援絕對路徑和相對路徑)
// 格式要求:file:// + 檔案路徑
// String image1 = "file:///path/to/your/car.png";
// String image2 = "file:///path/to/your/paint.png";
// 【方式三】使用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("---sync call for image editing, please wait a moment----");
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("Image saved to " + 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}替換為真實的業務空間ID,各地區的URL不同。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey="sk-xxx"
// 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/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 {
/*
* 映像輸入方式說明:
* 以下提供了三種圖片輸入方式,三選一即可
* 1. 使用公網URL - 適合已有公開可訪問的圖片
* 2. 使用本地檔案 - 適合本地開發測試
* 3. 使用Base64編碼 - 適合私人圖片或需要加密傳輸的情境
*/
// 【方式一】使用公網圖片 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";
// 【方式二】使用本地檔案(支援絕對路徑和相對路徑)
// 格式要求:file:// + 檔案路徑
// String image1 = "file:///path/to/your/car.png";
// String image2 = "file:///path/to/your/paint.png";
// 【方式三】使用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("---async call for image editing, creating task----");
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---waiting for task completion----");
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("Image saved to " + fileName);
}
}
}
}
public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
asyncCall();
}
}
響應樣本
1、建立任務的響應樣本
{
"requestId": "ccf4b2f4-bf30-9e13-9461-3a28c6a7bxxx",
"output": {
"task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx",
"task_status": "PENDING"
},
"status_code": 200,
"code": "",
"message": ""
}
2、查詢任務結果的響應樣本
URL 有效期間24小時,請及時下載並儲存映像。
{
"requestId": "60a08540-f1c1-9e76-8cd3-d5949db8cxxx",
"usage": {
"input_tokens": 18711,
"output_tokens": 2,
"total_tokens": 18713,
"image_count": 1,
"size": "2985*1405"
},
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
}
]
}
}
],
"task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx",
"task_status": "SUCCEEDED",
"finished": true,
"submit_time": "2026-03-31 19:57:58.840",
"scheduled_time": "2026-03-31 19:57:58.877",
"end_time": "2026-03-31 19:58:11.563"
},
"status_code": 200,
"code": "",
"message": ""
}
組圖產生
同步調用
請求樣本
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* wan2.7-image-pro 組圖產生 - 同步調用樣本(新加坡地區)
*/
public class Main {
static {
// 以下為新加坡地區的URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey="sk-xxx"
// 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/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 {
/*
* 映像輸入方式說明(圖生組圖情境):
* 以下提供了三種圖片輸入方式,三選一即可
* 1. 使用公網URL - 適合已有公開可訪問的圖片
* 2. 使用本地檔案 - 適合本地開發測試
* 3. 使用Base64編碼 - 適合私人圖片或需要加密傳輸的情境
*/
// 【方式一】使用公網圖片 URL
// String image1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp";
// 【方式二】使用本地檔案(支援絕對路徑和相對路徑)
// 格式要求:file:// + 檔案路徑
// String image1 = "file:///path/to/your/image.png";
// 【方式三】使用Base64編碼的圖片
// String image1 = encodeFile("/path/to/your/image.png");
// 構建文本輸入訊息(支援文生組圖以及圖生組圖,此處以文生組圖為例)
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Collections.singletonList(
Collections.singletonMap("text", "電影感組圖,記錄同一隻流浪橘貓,特徵必須前後一致。第一張:春天,橘貓穿梭在盛開的櫻花樹下;第二張:夏天,橘貓在老街的樹蔭下乘涼避暑;第三張:秋天,橘貓踩在滿地的金色落葉上;第四張:冬天,橘貓在雪地上走留下足跡。")
)).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("----sync call, please wait a moment----");
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("Image saved to " + 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}替換為真實的業務空間ID,各地區的URL不同。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey="sk-xxx"
// 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/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 {
/*
* 映像輸入方式說明(圖生組圖情境):
* 以下提供了三種圖片輸入方式,三選一即可
* 1. 使用公網URL - 適合已有公開可訪問的圖片
* 2. 使用本地檔案 - 適合本地開發測試
* 3. 使用Base64編碼 - 適合私人圖片或需要加密傳輸的情境
*/
// 【方式一】使用公網圖片 URL
// String image1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp";
// 【方式二】使用本地檔案(支援絕對路徑和相對路徑)
// 格式要求:file:// + 檔案路徑
// String image1 = "file:///path/to/your/image.png";
// 【方式三】使用Base64編碼的圖片
// String image1 = encodeFile("/path/to/your/image.png");
// 構建文本輸入訊息(支援文生組圖以及圖生組圖,此處以文生組圖為例)
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Collections.singletonList(
Collections.singletonMap("text", "電影感組圖,記錄同一隻流浪橘貓,特徵必須前後一致。第一張:春天,橘貓穿梭在盛開的櫻花樹下;第二張:夏天,橘貓在老街的樹蔭下乘涼避暑;第三張:秋天,橘貓踩在滿地的金色落葉上;第四張:冬天,橘貓在雪地上走留下足跡。")
)).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("----async call, creating task----");
taskResult = imageGeneration.asyncCall(param);
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
System.out.println("Task created: " + 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("Image saved to " + 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": ""
}
計費與限流
錯誤碼
如果模型調用失敗並返回報錯資訊,請參見錯誤碼進行解決。