全部產品
Search
文件中心

Alibaba Cloud Model Studio:通義萬相-通用影像編輯2.5

更新時間:Dec 06, 2025

通義萬相-通用影像編輯wan2.5模型僅需文本指令,即可基於單張或多張參考映像,實現主體一致的影像編輯、多圖融合等能力。

快速入口使用指南

模型概覽

模型功能

輸入樣本

輸出映像

單圖編輯

damotest2023_Portrait_photography_outdoors_fashionable_beauty_409ae3c1-19e8-4515-8e50-b3c9072e1282_2-轉換自-png

a26b226d-f044-4e95-a41c-d1c0d301c30b-轉換自-png

將花卉連衣裙換成一件複古風格的蕾絲長裙,領口和袖口有精緻的刺繡細節。

多圖融合

image

p1028883

將圖1中的鬧鐘放置到圖2的餐桌的花瓶旁邊位置

模型名稱

模型簡介

輸出映像規格

wan2.5-i2i-preview

萬相2.5 preview

支援單圖編輯、多圖融合

圖片格式:PNG。

映像解析度:

  • 通過 parameters.size 參數指定輸出映像的解析度,格式為寬*高(單位:像素)。

  • 若未指定解析度,系統將預設產生總像素為 1280*1280 的映像,並按以下規則保持寬高比(近似值):

    • 單圖輸入:寬高比與輸入映像一致;

    • 多圖輸入:寬高比與最後一張輸入映像一致。

說明

調用前,請查閱各地區支援的模型列表與價格

前提條件

在調用前,先擷取與配置 API Key,再配置API Key到環境變數(準備下線,併入配置 API Key)。如需通過SDK進行調用,請安裝DashScope SDK

重要

北京和新加坡地區擁有獨立的 API Key 請求地址,不可混用,跨地區調用將導致鑒權失敗或服務報錯。

HTTP調用

由於影像編輯任務耗時較長(通常為1-2分鐘),API採用非同步呼叫。整個流程包含 “建立任務 -> 輪詢擷取” 兩個核心步驟,具體如下:

具體耗時受限於排隊任務數和服務執行情況,請在擷取結果時耐心等待。

步驟1:建立任務擷取任務ID

新加坡地區POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis

北京地區POST https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis

說明
  • 建立成功後,使用介面返回的 task_id 查詢結果,task_id 有效期間為 24 小時。請勿重複建立任務,輪詢擷取即可。

請求參數

單圖編輯

 curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wan2.5-i2i-preview",
    "input": {
        "prompt": "將花卉連衣裙換成一件複古風格的蕾絲長裙,領口和袖口有精緻的刺繡細節。",
        "images": [
            "https://img.alicdn.com/imgextra/i2/O1CN01vHOj4h28jOxUJPwY8_!!6000000007968-49-tps-1344-896.webp"
        ]
    },
    "parameters": {
        "prompt_extend": true,
        "n": 1
    }
}'

多圖融合

 curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wan2.5-i2i-preview",
    "input": {
        "prompt": "將圖1中的鬧鐘放置到圖2的餐桌的花瓶旁邊位置",
        "images": [
            "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp",
            "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
        ]
    },
    "parameters": {
        "n": 1
    }
}'

要求標頭(Headers)

Content-Type string (必選)

請求內容類型。此參數必須設定為application/json

Authorization string(必選)

請求身份認證。介面使用阿里雲百鍊API-Key進行身份認證。樣本值:Bearer sk-xxxx。

X-DashScope-Async string (必選)

非同步處理配置參數。HTTP請求只支援非同步,必須設定為enable

重要

缺少此要求標頭將報錯:“current user api does not support synchronous calls”。

請求體(Request Body)

model string (必選)

模型名稱。詳情參見模型列表與價格

樣本值:wan2.5-i2i-preview。

input object (必選)

輸入的基本資料,如提示詞等。

屬性

prompt string (必選)

正向提示詞,用來描述產生映像中期望包含的元素和視覺特點。

支援中英文,長度不超過2000個字元,每個漢字/字母佔一個字元,超過部分會自動截斷。

提示詞的提示請參見文生圖Prompt指南

樣本值:一隻坐著的橘黃色的貓,表情愉悅,活潑可愛,逼真準確。

images array of string (必選)

映像URL數組。

  • 數組長度不超過3,即最多輸入3張圖片。

  • 多圖輸入時,按照數組順序定義映像順序。

映像限制:

  • 映像格式:JPEG、JPG、PNG(不支援透明通道)、BMP、WEBP。

  • 映像解析度:映像的寬高範圍均為[384, 5000]像素。

  • 檔案大小:不超過10MB。

支援的輸入格式:

  1. 使用公網可訪問URL

    • 支援 HTTP 或 HTTPS 協議。

    • 樣本值:http://wanx.alicdn.com/material/20250318/stylization_all_1.jpeg

  2. 傳入 Base 64 編碼映像後的字串

    • 格式:data:{MIME_type};base64,{base64_data}

    • 樣本:data:image/jpeg;base64,GDU7MtCZzEbTbmRZ...(僅示意,實際需傳入完整字串)

    • Base 64 編碼規範請參見映像傳入方式

negative_prompt string (可選)

反向提示詞,用來描述不希望在畫面中看到的內容,可以對畫面進行限制。

支援中英文,長度不超過500個字元,超過部分會自動截斷。

樣本值:低解析度、錯誤、最差品質、低品質、殘缺、多餘的手指、比例不良等。

parameters object (可選)

影像處理參數。如設定映像解析度、開啟prompt智能改寫、添加浮水印等。

屬性

size string (可選)

設定輸出映像的解析度,格式為寬*高。預設值為 1280*1280

  • 映像解析度:總像素在 [768*768, 1280*1280] 之間,且寬高比範圍為 [1:4, 4:1]。

  • 樣本值:1280*1280。

推薦解析度及對應寬高比

  • 1280*1280:1:1

  • 1024*1024:1:1

  • 800*1200:2:3

  • 1200*800:3:2

  • 960*1280:3:4

  • 1280*960:4:3

  • 720*1280:9:16

  • 1280*720:16:9

  • 1344*576:21:9

若未指定size,系統將預設產生總像素為 1280*1280 的映像,並按以下規則保持寬高比(近似值):

  • 單圖輸入:寬高比與輸入映像一致;

  • 多圖輸入:寬高比與最後一張輸入映像一致。

n integer (可選)

重要

n直接影響費用。n越大費用越高,請在調用前確認模型價格

產生圖片的數量。取值範圍為1~4張,預設為4。為控製成本,測試建議顯式設定為1。

watermark boolean (可選)

是否添加浮水印標識,浮水印位於圖片右下角,文案固定為“AI產生”。

  • false:預設值,不添加浮水印。

  • true:添加浮水印。

prompt_extend boolean (可選)

是否開啟prompt智能改寫。開啟後使用大模型對輸入prompt進行智能改寫,提升綜合表現,但會增加耗時。

  • true:預設值,開啟智能改寫。

  • false:不開啟智能改寫。

樣本值:true。

seed integer (可選)

隨機數種子,取值範圍是[0, 2147483647]

如果不提供,則演算法自動產生一個隨機數作為種子。如果提供,則根據n的值分別為n張圖片產生seed參數,例如n=4,演算法將分別產生seed、seed+1、seed+2、seed+3作為參數的圖片。

若需提升產生結果的可複現性,建議固定seed值。

請注意,由於模型產生具有機率性,即使使用相同 seed,也不能保證每次產生結果完全一致。

響應參數

成功響應

請儲存 task_id,用於查詢任務狀態與結果。

{
    "output": {
        "task_status": "PENDING",
        "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
    },
    "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}

異常響應

建立任務失敗,請參見錯誤資訊進行解決。

{
    "code":"InvalidApiKey",
    "message":"Invalid API-key provided.",
    "request_id":"fb53c4ec-1c12-4fc4-a580-xxxxxx"
}

output object

任務輸出資訊。

屬性

task_id string

任務ID。查詢有效期間24小時。

task_status string

任務狀態。

枚舉值

  • PENDING:任務排隊中

  • RUNNING:任務處理中

  • SUCCEEDED:任務執行成功

  • FAILED:任務執行失敗

  • CANCELED:任務已取消

  • UNKNOWN:任務不存在或狀態未知

request_id string

請求唯一標識。可用於請求明細溯源和問題排查。

code string

請求失敗的錯誤碼。請求成功時不會返回此參數,詳情請參見錯誤資訊

message string

請求失敗的詳細資料。請求成功時不會返回此參數,詳情請參見錯誤資訊

步驟2:根據任務ID查詢結果

新加坡地區GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id}

北京地區GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}

說明
  • 輪詢建議:映像產生過程約需數分鐘,建議採用輪詢機制,並設定合理的查詢間隔(如 10 秒)來擷取結果。

  • 任務狀態流轉:PENDING(排隊中)→ RUNNING(處理中)→ SUCCEEDED(成功)/ FAILED(失敗)。

  • 結果連結:任務成功後返回映像連結,有效期間為 24 小時。建議在擷取連結後立即下載並轉存至永久儲存(如阿里雲 OSS)。

請求參數

查詢任務結果

請將86ecf553-d340-4e21-xxxxxxxxx替換為真實的task_id。

新加坡和北京地區的API Key不同。擷取與配置 API Key
以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為https://dashscope.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx
curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
要求標頭(Headers)

Authorization string(必選)

請求身份認證。介面使用阿里雲百鍊API-Key進行身份認證。樣本值:Bearer sk-xxxx。

URL路徑參數(Path parameters)

task_id string(必選)

任務ID。

響應參數

任務執行成功

映像URL僅保留24小時,逾時後會被自動清除,請及時儲存產生的映像。

{
    "request_id": "d1f2a1be-9c58-48af-b43f-xxxxxx",
    "output": {
        "task_id": "7f4836cd-1c47-41b3-b3a4-xxxxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2025-09-23 22:14:10.800",
        "scheduled_time": "2025-09-23 22:14:10.825",
        "end_time": "2025-09-23 22:15:23.456",
        "results": [
            {
                "orig_prompt": "將花卉連衣裙換成一件複古風格的蕾絲長裙,領口和袖口有精緻的刺繡細節。",
                "actual_prompt": "將粉色褶皺連衣裙替換為一件複古風格的蕾絲長裙,領口和袖口帶有精緻的刺繡細節,保持人物髮型、妝容和姿態不變,整體風格與原圖的柔和色調和古典氛圍一致。",
                "url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"
            }
        ],
        "task_metrics": {
            "TOTAL": 1,
            "FAILED": 0,
            "SUCCEEDED": 1
        }
    },
    "usage": {
        "image_count": 1
    }
}

任務執行失敗

若任務執行失敗,task_status將置為 FAILED,並提供錯誤碼和資訊。請參見錯誤資訊進行解決。

{
    "request_id": "e5d70b02-ebd3-98ce-9fe8-759d7d7b107d",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-xxxxxx",
        "task_status": "FAILED",
        "code": "InvalidParameter",
        "message": "xxxxxx",
        "task_metrics": {
            "TOTAL": 4,
            "SUCCEEDED": 0,
            "FAILED": 4
        }
    }
}

任務部分失敗

模型可以在一次任務中產生多張圖片。只要有一張圖片產生成功,任務狀態將標記為SUCCEEDED,並且返回相應的映像URL。對於產生失敗的圖片,結果中會返回相應的失敗原因。同時在usage統計中,只會對成功的結果計數。請參見錯誤資訊進行解決。

{
    "request_id": "85eaba38-0185-99d7-8d16-xxxxxx",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-xxxxxx",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/123/a1.png"
            },
            {
                "code": "InternalError.Timeout",
                "message": "An internal timeout error has occured during execution, please try again later or contact service support."
            }
        ],
        "task_metrics": {
            "TOTAL": 2,
            "SUCCEEDED": 1,
            "FAILED": 1
        }
    },
    "usage": {
        "image_count": 1
    }
}

任務查詢到期

task_id查詢有效期間為 24 小時,逾時後將無法查詢,返回以下報錯資訊。

{
    "request_id": "a4de7c32-7057-9f82-8581-xxxxxx",
    "output": {
        "task_id": "502a00b1-19d9-4839-a82f-xxxxxx",
        "task_status": "UNKNOWN"
    }
}

output object

任務輸出資訊。

屬性

task_id string

任務ID。查詢有效期間24小時。

task_status string

任務狀態。

枚舉值

  • PENDING:任務排隊中

  • RUNNING:任務處理中

  • SUCCEEDED:任務執行成功

  • FAILED:任務執行失敗

  • CANCELED:任務已取消

  • UNKNOWN:任務不存在或狀態未知

submit_time string

任務提交時間。時區為UTC+8,格式為 YYYY-MM-DD HH:mm:ss.SSS。

scheduled_time string

任務執行時間。時區為UTC+8,格式為 YYYY-MM-DD HH:mm:ss.SSS。

end_time string

任務完成時間。時區為UTC+8,格式為 YYYY-MM-DD HH:mm:ss.SSS。

results array of object

任務結果清單,包括映像URL、prompt、部分任務執行失敗報錯資訊等。

屬性

orig_prompt string

原始輸入的prompt,對應請求參數prompt

actual_prompt string

開啟 prompt 智能改寫後,返回實際使用的最佳化後 prompt。若未開啟該功能,則不返回此欄位。

url string

模型產生圖片的URL地址。

code string

映像錯誤碼。部分任務執行失敗時會返回該欄位。

message string

映像錯誤資訊。部分任務執行失敗時會返回該欄位。

task_metrics object

任務結果統計。

屬性

TOTAL integer

總的任務數。

SUCCEEDED integer

任務狀態為成功的任務數。

FAILED integer

任務狀態為失敗的任務數。

code string

請求失敗的錯誤碼。請求成功時不會返回此參數,詳情請參見錯誤資訊

message string

請求失敗的詳細資料。請求成功時不會返回此參數,詳情請參見錯誤資訊

usage object

輸出資訊統計。只對成功的結果計數。

屬性

image_count integer

模型成功產生圖片的數量。計費公式:費用 = 圖片數量 × 單價。

request_id string

請求唯一標識。可用於請求明細溯源和問題排查。

DashScope SDK調用

SDK 的參數命名與HTTP調用基本一致,參數結構根據語言特性進行封裝。

由於影像編輯任務耗時約30秒~60秒,SDK 在底層封裝了 HTTP 非同步呼叫流程,支援同步、非同步兩種調用方式。

具體耗時受限於排隊任務數和服務執行情況,請在擷取結果時耐心等待。

Python SDK調用

重要

請確保 DashScope Python SDK 版本不低於 1.25.2

若版本過低,可能會觸發 “url error, please check url!” 等錯誤。請參考安裝或升級SDK進行更新。

同步調用

請求樣本

本樣本支援三種映像輸入方式:公網URL、Base64編碼、本地檔案路徑。

import base64
import mimetypes
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath

import dashscope
import requests
from dashscope import ImageSynthesis
import os

# 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.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")

# --- 輸入圖片:使用 Base 64 編碼 ---
# 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_url_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp"
image_url_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"

# 【方式二】使用本地檔案(支援絕對路徑和相對路徑)
# 格式要求:file:// + 檔案路徑
# 樣本(絕對路徑):
# image_url_1 = "file://" + "/path/to/your/image_1.png"     # Linux/macOS
# image_url_2 = "file://" + "C:/path/to/your/image_2.png"  # Windows
# 樣本(相對路徑):
# image_url_1 = "file://" + "./image_1.png"                 # 以實際路徑為準
# image_url_2 = "file://" + "./image_2.png"                # 以實際路徑為準

# 【方式三】使用Base64編碼的圖片
# image_url_1 = encode_file("./image_1.png")               # 以實際路徑為準
# image_url_2 = encode_file("./image_2.png")              # 以實際路徑為準

print('----sync call, please wait a moment----')
rsp = ImageSynthesis.call(api_key=api_key,
                          model="wan2.5-i2i-preview",
                          prompt="將圖1中的鬧鐘放置到圖2的餐桌的花瓶旁邊位置",
                          images=[image_url_1, image_url_2],
                          negative_prompt="",
                          n=1,
                          # size="1280*1280",
                          prompt_extend=True,
                          watermark=False,
                          seed=12345)
print('response: %s' % rsp)
if rsp.status_code == HTTPStatus.OK:
    # 在目前的目錄下儲存圖片
    for result in rsp.output.results:
        file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
        with open('./%s' % file_name, 'wb+') as f:
            f.write(requests.get(result.url).content)
else:
    print('sync_call Failed, status_code: %s, code: %s, message: %s' %
          (rsp.status_code, rsp.code, rsp.message))
響應樣本
url 有效期間24小時,請及時下載映像。
{
    "status_code": 200,
    "request_id": "8ad45834-4321-44ed-adf5-xxxxxx",
    "code": null,
    "message": "",
    "output": {
        "task_id": "3aff9ebd-35fc-4339-98a3-xxxxxx",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
                "orig_prompt": "將圖1中的鬧鐘放置到圖2的餐桌的花瓶旁邊位置",
                "actual_prompt": "將圖1中的藍色鬧鐘放置在圖2餐桌的花瓶右側,靠近桌布邊緣的位置,保持鬧鐘朝向鏡頭,與案頭平行,陰影自然投射於案頭。"
            }
        ],
        "submit_time": "2025-10-23 16:18:16.009",
        "scheduled_time": "2025-10-23 16:18:16.040",
        "end_time": "2025-10-23 16:19:09.591",
        "task_metrics": {
            "TOTAL": 1,
            "FAILED": 0,
            "SUCCEEDED": 1
        }
    },
    "usage": {
        "image_count": 1
    }
}

非同步呼叫

本樣本使用公網URL方式傳入圖片。

請求樣本
import os
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import dashscope
import requests
from dashscope import ImageSynthesis

# 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.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")

# 使用公網圖片 URL
image_url_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp"
image_url_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"


def async_call():
    print('----create task----')
    task_info = create_async_task()
    print('----wait task----')
    wait_async_task(task_info)


# 建立非同步任務
def create_async_task():
    rsp = ImageSynthesis.async_call(api_key=api_key,
                                    model="wan2.5-i2i-preview",
                                    prompt="將圖1中的鬧鐘放置到圖2的餐桌的花瓶旁邊位置",
                                    images=[image_url_1, image_url_2],
                                    negative_prompt="",
                                    n=1,
                                    # size="1280*1280",
                                    prompt_extend=True,
                                    watermark=False,
                                    seed=12345)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))
    return rsp


# 等待非同步任務結束
def wait_async_task(task):
    rsp = ImageSynthesis.wait(task=task, api_key=api_key)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output)
        # save file to current directory
        for result in rsp.output.results:
            file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
            with open('./%s' % file_name, 'wb+') as f:
                f.write(requests.get(result.url).content)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))


# 擷取非同步任務資訊
def fetch_task_status(task):
    status = ImageSynthesis.fetch(task=task, api_key=api_key)
    print(status)
    if status.status_code == HTTPStatus.OK:
        print(status.output.task_status)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (status.status_code, status.code, status.message))


# 取消非同步任務,只有處於PENDING狀態的任務才可以取消
def cancel_task(task):
    rsp = ImageSynthesis.cancel(task=task, api_key=api_key)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output.task_status)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))


if __name__ == '__main__':
    async_call()
響應樣本

1、建立任務的響應樣本

{
	"status_code": 200,
	"request_id": "31b04171-011c-96bd-ac00-f0383b669cc7",
	"code": "",
	"message": "",
	"output": {
		"task_id": "4f90cf14-a34e-4eae-xxxxxxxx",
		"task_status": "PENDING",
		"results": []
	},
	"usage": null
}

2、查詢任務結果的響應樣本

url 有效期間24小時,請及時下載映像。
{
    "status_code": 200,
    "request_id": "8ad45834-4321-44ed-adf5-xxxxxx",
    "code": null,
    "message": "",
    "output": {
        "task_id": "3aff9ebd-35fc-4339-98a3-xxxxxx",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
                "orig_prompt": "將圖1中的鬧鐘放置到圖2的餐桌的花瓶旁邊位置",
                "actual_prompt": "將圖1中的藍色鬧鐘放置在圖2餐桌的花瓶右側,靠近桌布邊緣的位置,保持鬧鐘朝向鏡頭,與案頭平行,陰影自然投射於案頭。"
            }
        ],
        "submit_time": "2025-10-23 16:18:16.009",
        "scheduled_time": "2025-10-23 16:18:16.040",
        "end_time": "2025-10-23 16:19:09.591",
        "task_metrics": {
            "TOTAL": 1,
            "FAILED": 0,
            "SUCCEEDED": 1
        }
    },
    "usage": {
        "image_count": 1
    }
}

Java SDK調用

重要

請確保 DashScope Java SDK 版本不低於 2.22.2

若版本過低,可能會觸發 “url error, please check url!” 等錯誤。請參考安裝或升級SDK進行更新。

同步調用

請求樣本

本樣本支援三種映像輸入方式:公網URL、Base64編碼、本地檔案路徑。

// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

public class Image2Image {

    static {
        // 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl = "https://dashscope-intl.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");

    /**
     * 映像輸入方式說明:三選一即可
     *
     * 1. 使用公網URL - 適合已有公開可訪問的圖片
     * 2. 使用本地檔案 - 適合本地開發測試
     * 3. 使用Base64編碼 - 適合私人圖片或需要加密傳輸的情境
     */

    //【方式一】公網URL
    static String imageUrl_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp";
    static String imageUrl_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp";

    //【方式二】本地檔案路徑(file://+絕對路徑 or file:///+絕對路徑)
    // static String imageUrl_1 = "file://" + "/your/path/to/image_1.png";    // Linux/macOS
    // static String imageUrl_2 = "file:///" + "C:/your/path/to/image_2.png";  // Windows

    //【方式三】Base64編碼
    // static String imageUrl_1 = encodeFile("/your/path/to/image_1.png");
    // static String imageUrl_2 = encodeFile("/your/path/to/image_2.png");

    // 設定待編輯的圖片列表
    static List<String> imageUrls = new ArrayList<>();
    static {
        imageUrls.add(imageUrl_1);
        imageUrls.add(imageUrl_2);
    }

    public static void syncCall() {
        // 設定parameters參數
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        parameters.put("watermark", false);
        parameters.put("seed", "12345");

        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.5-i2i-preview")
                        .prompt("將圖1中的鬧鐘放置到圖2的餐桌的花瓶旁邊位置")
                        .images(imageUrls)
                        .n(1)
                         //.size("1280*1280")
                        .negativePrompt("")
                        .parameters(parameters)
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            System.out.println("---sync call, please wait a moment----");
            result = imageSynthesis.call(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
    }

    /**
     * 將檔案編碼為Base64字串
     * @param filePath 檔案路徑
     * @return Base64字串,格式為 data:{MIME_type};base64,{base64_data}
     */
    public static String encodeFile(String filePath) {
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            throw new IllegalArgumentException("檔案不存在: " + filePath);
        }
        // 檢測MIME類型
        String mimeType = null;
        try {
            mimeType = Files.probeContentType(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("無法檢測檔案類型: " + filePath);
        }
        if (mimeType == null || !mimeType.startsWith("image/")) {
            throw new IllegalArgumentException("不支援或無法識別的映像格式");
        }
        // 讀取檔案內容並編碼
        byte[] fileBytes = null;
        try{
            fileBytes = Files.readAllBytes(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("無法讀取檔案內容: " + filePath);
        }

        String encodedString = Base64.getEncoder().encodeToString(fileBytes);
        return "data:" + mimeType + ";base64," + encodedString;
    }

    public static void main(String[] args) {
        syncCall();
    }
}
響應樣本
url 有效期間24小時,請及時下載映像。
{
    "request_id": "d362685b-757f-4eac-bab5-xxxxxx",
    "output": {
        "task_id": "bfa7fc39-3d87-4fa7-b1e6-xxxxxx",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "orig_prompt": "將圖1中的鬧鐘放置到圖2的餐桌的花瓶旁邊位置",
                "actual_prompt": "將圖1中的藍色鬧鐘放置在圖2餐桌的花瓶右側,靠近桌布邊緣的位置,保持鬧鐘正面朝向鏡頭,與花瓶平行擺放。",
                "url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"
            }
        ],
        "task_metrics": {
            "TOTAL": 1,
            "SUCCEEDED": 1,
            "FAILED": 0
        }
    },
    "usage": {
        "image_count": 1
    }
}

非同步呼叫

本樣本使用公網URL方式傳入圖片。

請求樣本
// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisListResult;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Image2Image {

    static {
        // 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl = "https://dashscope-intl.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");

    //公網URL
    static String imageUrl_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp";
    static String imageUrl_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp";

    // 設定待編輯的圖片列表
    static List<String> imageUrls = new ArrayList<>();
    static {
        imageUrls.add(imageUrl_1);
        imageUrls.add(imageUrl_2);
    }

    public static void asyncCall() {
        // 設定parameters參數
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        parameters.put("watermark", false);
        parameters.put("seed", "12345");

        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.5-i2i-preview")
                        .prompt("將圖1中的鬧鐘放置到圖2的餐桌的花瓶旁邊位置")
                        .images(imageUrls)
                        .n(1)
                        //.size("1280*1280")
                        .negativePrompt("")
                        .parameters(parameters)
                        .build();
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            System.out.println("---async call, please wait a moment----");
            result = imageSynthesis.asyncCall(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }

        System.out.println(JsonUtils.toJson(result));

        String taskId = result.getOutput().getTaskId();

        System.out.println("taskId=" + taskId);


        try {
            result = imageSynthesis.wait(taskId, apiKey);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
        System.out.println(JsonUtils.toJson(result.getOutput()));
    }

    public static void listTask() throws ApiException, NoApiKeyException {
        ImageSynthesis is = new ImageSynthesis();
        AsyncTaskListParam param = AsyncTaskListParam.builder().build();
        param.setApiKey(apiKey);
        ImageSynthesisListResult result = is.list(param);
        System.out.println(result);
    }

    public void fetchTask(String taskId) throws ApiException, NoApiKeyException {
        ImageSynthesis is = new ImageSynthesis();
        // 如果已設定 DASHSCOPE_API_KEY 為環境變數,apiKey 可為空白。
        ImageSynthesisResult result = is.fetch(taskId, apiKey);
        System.out.println(result.getOutput());
        System.out.println(result.getUsage());
    }


    public static void main(String[] args) {
        asyncCall();
    }
}
響應樣本

1、建立任務的響應樣本

{
	"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
	"output": {
		"task_id": "7277e20e-aa01-4709-xxxxxxxx",
		"task_status": "PENDING"
	}
}

2、查詢任務結果的響應樣本

url 有效期間24小時,請及時下載圖片。
{
    "request_id": "d362685b-757f-4eac-bab5-xxxxxx",
    "output": {
        "task_id": "bfa7fc39-3d87-4fa7-b1e6-xxxxxx",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "orig_prompt": "將圖1中的鬧鐘放置到圖2的餐桌的花瓶旁邊位置",
                "actual_prompt": "將圖1中的藍色鬧鐘放置在圖2餐桌的花瓶右側,靠近桌布邊緣的位置,保持鬧鐘正面朝向鏡頭,與花瓶平行擺放。",
                "url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"
            }
        ],
        "task_metrics": {
            "TOTAL": 1,
            "SUCCEEDED": 1,
            "FAILED": 0
        }
    },
    "usage": {
        "image_count": 1
    }
}

使用限制

  • 資料時效:任務task_id和 映像url均只保留 24 小時,到期後將無法查詢或下載。

  • 內容審核:輸入prompt、映像和輸出映像均會經過Alibaba Content Security Service審核,包含違規內容的請求將報錯“IPInfringementSuspect”或“DataInspectionFailed”,具體參見錯誤資訊

  • 網路訪問配置:映像連結儲存於阿里雲 OSS,如果業務系統因安全性原則無法訪問阿里雲OSS連結,請將以下 OSS 網域名稱加入網路訪問白名單。

    # OSS網域名稱列表
    dashscope-result-bj.oss-cn-beijing.aliyuncs.com
    dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com
    dashscope-result-sh.oss-cn-shanghai.aliyuncs.com
    dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com
    dashscope-result-zjk.oss-cn-zhangjiakou.aliyuncs.com
    dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com
    dashscope-result-hy.oss-cn-heyuan.aliyuncs.com
    dashscope-result-cd.oss-cn-chengdu.aliyuncs.com
    dashscope-result-gz.oss-cn-guangzhou.aliyuncs.com
    dashscope-result-wlcb-acdr-1.oss-cn-wulanchabu-acdr-1.aliyuncs.com

錯誤碼

如果模型調用失敗並返回報錯資訊,請參見錯誤資訊進行解決。

常見問題

Q:之前使用通用影像編輯 2.1,現在切換到 wan2.5 模型,SDK調用方式需要調整嗎?

A:需要調整。兩個版本的參數設計不同:

Q: 如何查看模型調用量?

A: 模型調用完一小時後,請在模型觀測(新加坡)模型觀測(北京)頁面,查看模型的調用次數、成功率等指標。操作指引:如何查看模型調用記錄?