全部產品
Search
文件中心

Alibaba Cloud Model Studio:通義千問-影像編輯API參考

更新時間:Jan 28, 2026

通義千問-影像編輯模型支援多圖輸入和多圖輸出,可精確修改圖內文字、增刪或移動物體、改變主體動作、遷移圖片風格及增強畫面細節。

模型概覽

輸入圖1

輸入圖2

輸入圖3

輸出映像(多圖)

image99

image98

image89

image100

imageout2

輸入提示詞:圖1中的女生穿著圖2中的黑色裙子按圖3的姿勢坐下。

模型名稱

模型簡介

輸出映像規格

qwen-image-edit-max

當前與qwen-image-edit-max-2026-01-16能力相同

支援單圖編輯和多圖融合。

格式:PNG
解析度

  • 可指定:通過 parameters.size 參數指定輸出映像的寬*高(單位:像素)。

  • 預設(不指定時):總像素接近 1024*1024,寬高比與輸入圖(多圖輸入時為最後一張)一致。

qwen-image-edit-max-2026-01-16

qwen-image-edit-plus

當前與qwen-image-edit-plus-2025-10-30能力相同

qwen-image-edit-plus-2025-12-15

qwen-image-edit-plus-2025-10-30

qwen-image-edit

支援單圖編輯和多圖融合。

  • 僅支援輸出 1 張圖片。

  • 不支援自訂解析度。

格式:PNG

解析度不可指定。建置規則同上方的預設規則。

說明

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

前提條件

在調用前,您需要擷取API Key,再配置API Key到環境變數(準備下線,併入配置 API Key)

如需通過SDK進行調用,請安裝DashScope SDK。目前,該SDK已支援Python和Java。

重要

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

HTTP調用

新加坡地區:POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

北京地區:POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

請求參數

單圖編輯

此處以使用qwen-image-edit-max模型輸出2張圖片為例。

curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
    "model": "qwen-image-edit-max",
    "input": {
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/fpakfo/image36.webp"
                    },
                    {
                        "text": "產生一張符合深度圖的映像,遵循以下描述:一輛紅色的破舊的單車停在一條泥濘的小路上,背景是茂密的原始森林"
                    }
                ]
            }
        ]
    },
    "parameters": {
        "n": 2,
        "negative_prompt": " ",
        "prompt_extend": true,
        "watermark": false,
        "size": "1536*1024"
    }
}'

多圖融合

此處以使用qwen-image-edit-max模型輸出2張圖片為例。

curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
    "model": "qwen-image-edit-max",
    "input": {
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/thtclx/input1.png"
                    },
                    {
                        "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/iclsnx/input2.png"
                    },
                    {
                        "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/gborgw/input3.png"
                    },
                    {
                        "text": "圖1中的女生穿著圖2中的黑色裙子按圖3的姿勢坐下"
                    }
                ]
            }
        ]
    },
    "parameters": {
        "n": 2,
        "negative_prompt": " ",
        "prompt_extend": true,
        "watermark": false,
        "size": "1024*1536"
    }
}'
要求標頭(Headers)

Content-Type string (必選)

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

Authorization string(必選)

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

請求體(Request Body)

model string (必選)

模型名稱,樣本值qwen-image-edit-max。

input object (必選)

輸入參數對象,包含以下欄位:

屬性

messages array (必選)

請求內容數組。當前僅支援單輪對話,因此數組內有且只有一個對象,該對象包含rolecontent兩個屬性。

屬性

role string (必選)

訊息寄件者角色,必須設定為user

content array (必選)

訊息內容,包含1-3張映像,格式為 {"image": "..."};以及單個編輯指令,格式為 {"text": "..."}

屬性

image string (必選)

輸入映像的 URL 或 Base 64 編碼資料。支援傳入1-3張映像。

多圖輸入時,按照數組順序定義映像順序,輸出映像的比例以最後一張為準。

映像要求:

  • 映像格式:JPG、JPEG、PNG、BMP、TIFF、WEBP和GIF。

    輸出映像為PNG格式,對於GIF動圖,僅處理其第一幀。
  • 映像解析度:為獲得最佳效果,建議映像的寬和高均在384像素至3072像素之間。解析度過低可能導致產生效果模糊,過高則會增加處理時間長度。

  • 映像大小:不超過10MB。

支援的輸入格式:

  1. 公網可訪問的URL

    • 支援 HTTP 和 HTTPS 協議。

    • 樣本值:https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/fpakfo/image36.webp

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

text string (必選)

正向提示詞,用於描述期望產生的映像內容、風格和構圖。

支援中英文,長度不超過800個字元,每個漢字、字母、數字或符號計為一個字元,超過部分會自動截斷。

樣本值:圖1中的女生穿著圖2中的黑色裙子按圖3的姿勢坐下,保持其服裝、髮型和表情不變,動作自然流暢。

注意:僅支援傳入一個text,不傳或傳入多個將報錯。

parameters object (可選)

控製圖像產生的附加參數。

屬性

n integer (可選)

輸出映像的數量,預設值為1。

對於qwen-image-edit-max、qwen-image-edit-plus系列模型,可選擇輸出1-6張圖片。

對於qwen-image-edit,僅支援輸出1張圖片。

negative_prompt string (可選)

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

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

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

size string (可選)

設定輸出映像的解析度,格式為寬*高,例如"1024*1536"。寬和高的取值範圍均為[512, 2048]像素。

常見比例推薦解析度

  • 1:1: 1024*1024、1536*1536

  • 2:3: 768*1152、1024*1536

  • 3:2: 1152*768、1536*1024

  • 3:4: 960*1280、1080*1440

  • 4:3: 1280*960、1440*1080

  • 9:16: 720*1280、1080*1920

  • 16:9: 1280*720、1920*1080

  • 21:9: 1344*576、2048*872

預設行為:若不設定,輸出映像將保持與輸入映像(多圖輸入時為最後一張)相似的長寬比,接近1024*1024解析度。

支援模型:qwen-image-edit-max、qwen-image-edit-plus系列模型。

prompt_extend bool (可選)

是否開啟提示詞智能改寫,預設值為 true。開啟後,模型會最佳化正向提示詞(text),對描述較簡單的提示詞效果提升明顯。

支援模型:qwen-image-edit-max、qwen-image-edit-plus系列模型。

watermark bool (可選)

是否在映像右下角添加 "Qwen-Image" 浮水印。預設值為 false。浮水印樣式如下:

1

seed integer (可選)

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

使用相同的seed參數值可使產生內容保持相對穩定。若不提供,演算法將自動使用隨機數種子。

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

響應參數

任務執行成功

任務資料(如任務狀態、映像URL等)僅保留24小時,逾時後會被自動清除。請您務必及時儲存產生的映像。

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxx"
                        },
                        {
                            "image": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxx"
                        }
                    ]
                }
            }
        ]
    },
    "usage": {
        "width": 1536,
        "image_count": 2,
        "height": 1024
    },
    "request_id": "bf37ca26-0abe-98e4-8065-xxxxxx"
}

任務執行異常

如果因為某種原因導致任務執行失敗,將返回相關資訊,可以通過code和message欄位明確指示錯誤原因。請參見錯誤資訊進行解決。

{
    "request_id": "31f808fd-8eef-9004-xxxxx",
    "code": "InvalidApiKey",
    "message": "Invalid API-key provided."
}

output object

包含模型產生結果。

屬性

choices array

結果選項列表。

屬性

finish_reason string

任務停止原因,自然停止時為stop

message object

模型返回的訊息。

屬性

role string

訊息的角色,固定為assistant

content array

訊息內容,包含產生的映像資訊。

屬性

image string

產生映像的 URL,格式為PNG。連結有效期間為24小時,請及時下載並儲存映像。

usage object

本次調用的資源使用方式,僅調用成功時返回。

屬性

image_count integer

產生映像的張數。

width integer

產生映像的寬度(像素)。

height integer

產生映像的高度(像素)。

request_id string

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

code string

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

message string

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

DashScope SDK調用

SDK 的參數命名與HTTP介面基本一致,參數結構根據語言特性進行封裝,完整參數列表請參見通義千問 API 參考

Python SDK調用

說明
  • 推薦安裝最新版DashScope Python SDK,否則可能運行報錯:安裝或升級SDK

  • 不支援非同步介面。

請求樣本

通過公網URL傳入圖片

import json
import os
import dashscope
from dashscope import MultiModalConversation

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

# 模型支援輸入1-3張圖片
messages = [
    {
        "role": "user",
        "content": [
            {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/thtclx/input1.png"},
            {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/iclsnx/input2.png"},
            {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/gborgw/input3.png"},
            {"text": "圖1中的女生穿著圖2中的黑色裙子按圖3的姿勢坐下"}
        ]
    }
]

# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")

# qwen-image-edit-max、qwen-image-edit-plus系列支援輸出1-6張圖片,此處以2張為例
response = MultiModalConversation.call(
    api_key=api_key,
    model="qwen-image-edit-max",
    messages=messages,
    stream=False,
    n=2,
    watermark=False,
    negative_prompt=" ",
    prompt_extend=True,
    size="1024*1536",
)

if response.status_code == 200:
    # 如需查看完整響應,請取消下行注釋
    # print(json.dumps(response, ensure_ascii=False))
    for i, content in enumerate(response.output.choices[0].message.content):
        print(f"輸出映像{i+1}的URL:{content['image']}")
else:
    print(f"HTTP返回碼:{response.status_code}")
    print(f"錯誤碼:{response.code}")
    print(f"錯誤資訊:{response.message}")
    print("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code")

通過Base64編碼傳入圖片

import json
import os
import dashscope
from dashscope import MultiModalConversation
import base64
import mimetypes

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


# ---用於 Base 64 編碼 ---
# 格式為 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("不支援或無法識別的映像格式")

    try:
        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}"
    except IOError as e:
        raise IOError(f"讀取檔案時出錯: {file_path}, 錯誤: {str(e)}")


# 擷取映像的 Base 64 編碼
# 調用編碼函數,請將 "/path/to/your/image.png" 替換為您的本地圖片檔案路徑,否則無法運行
image = encode_file("/path/to/your/image.png")

messages = [
    {
        "role": "user",
        "content": [
            {"image": image},
            {"text": "產生一張符合深度圖的映像,遵循以下描述:一輛紅色的破舊的單車停在一條泥濘的小路上,背景是茂密的原始森林"}
        ]
    }
]

# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")

# qwen-image-edit-max、qwen-image-edit-plus系列支援輸出1-6張圖片,此處以2張為例
response = MultiModalConversation.call(
    api_key=api_key,
    model="qwen-image-edit-max",
    messages=messages,
    stream=False,
    n=2,
    watermark=False,
    negative_prompt=" ",
    prompt_extend=True,
    size="1536*1024",
)

if response.status_code == 200:
    # 如需查看完整響應,請取消下行注釋
    # print(json.dumps(response, ensure_ascii=False))
    for i, content in enumerate(response.output.choices[0].message.content):
        print(f"輸出映像{i+1}的URL:{content['image']}")
else:
    print(f"HTTP返回碼:{response.status_code}")
    print(f"錯誤碼:{response.code}")
    print(f"錯誤資訊:{response.message}")
    print("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code")

通過URL下載映像

# 需要安裝requests以下載映像: pip install requests
import requests


def download_image(image_url, save_path='output.png'):
    try:
        response = requests.get(image_url, stream=True, timeout=300)  # 設定逾時
        response.raise_for_status()  # 如果HTTP狀態代碼不是200,則引發異常
        with open(save_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        print(f"映像已成功下載到: {save_path}")

    except requests.exceptions.RequestException as e:
        print(f"映像下載失敗: {e}")


image_url = "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxx"
download_image(image_url, save_path='output.png')

響應樣本

映像連結的有效期間為24小時,請及時下載映像。

input_tokensoutput_tokenscharacters為相容欄位,當前固定為0。
{
    "status_code": 200,
    "request_id": "fa41f9f9-3cb6-434d-a95d-4ae6b9xxxxxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com/xxx.png?Expires=xxx"
                        },
                        {
                            "image": "https://dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com/xxx.png?Expires=xxx"
                        }
                    ]
                }
            }
        ],
        "audio": null
    },
    "usage": {
        "input_tokens": 0,
        "output_tokens": 0,
        "characters": 0,
        "height": 1536,
        "image_count": 2,
        "width": 1024
    }
}

Java SDK調用

說明

推薦安裝最新版DashScope Java SDK,否則可能運行報錯:安裝或升級SDK

請求樣本

通過公網URL傳入圖片

import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

public class QwenImageEdit {

    static {
        // 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
    }
    
    // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    // 若沒有配置環境變數,請用百鍊 API Key 將下行替換為:apiKey="sk-xxx"
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    public static void call() throws ApiException, NoApiKeyException, UploadFileException, IOException {

        MultiModalConversation conv = new MultiModalConversation();

        // 模型支援輸入1-3張圖片
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/thtclx/input1.png"),
                        Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/iclsnx/input2.png"),
                        Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/gborgw/input3.png"),
                        Collections.singletonMap("text", "圖1中的女生穿著圖2中的黑色裙子按圖3的姿勢坐下")
                )).build();
        // qwen-image-edit-max、qwen-image-edit-plus系列支援輸出1-6張圖片,此處以2張為例
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("watermark", false);
        parameters.put("negative_prompt", " ");
        parameters.put("n", 2);
        parameters.put("prompt_extend", true);
        parameters.put("size", "1024*1536");

        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(apiKey)
                .model("qwen-image-edit-max")
                .messages(Collections.singletonList(userMessage))
                .parameters(parameters)
                .build();

        MultiModalConversationResult result = conv.call(param);
        // 如需查看完整響應,請取消下行注釋
        // System.out.println(JsonUtils.toJson(result));
        List<Map<String, Object>> contentList = result.getOutput().getChoices().get(0).getMessage().getContent();
        int imageIndex = 1;
        for (Map<String, Object> content : contentList) {
            if (content.containsKey("image")) {
                System.out.println("輸出映像" + imageIndex + "的URL:" + content.get("image"));
                imageIndex++;
            }
        }
    }

    public static void main(String[] args) {
        try {
            call();
        } catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

通過Base64編碼傳入圖片

import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

public class QwenImageEdit {

    static {
        // 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
    }
    
    // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    // 若沒有配置環境變數,請用百鍊 API Key 將下行替換為:apiKey="sk-xxx"
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    public static void call() throws ApiException, NoApiKeyException, UploadFileException, IOException {

        // 請將 "/path/to/your/image.png" 替換為您的本地圖片檔案路徑,否則無法運行
        String image = encodeFile("/path/to/your/image.png");

        MultiModalConversation conv = new MultiModalConversation();

        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        Collections.singletonMap("image", image),
                        Collections.singletonMap("text", "產生一張符合深度圖的映像,遵循以下描述:一輛紅色的破舊的單車停在一條泥濘的小路上,背景是茂密的原始森林")
                )).build();
        // qwen-image-edit-max、qwen-image-edit-plus系列支援輸出1-6張圖片,此處以2張為例
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("watermark", false);
        parameters.put("negative_prompt", " ");
        parameters.put("n", 2);
        parameters.put("prompt_extend", true);
        parameters.put("size", "1536*1024");

        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(apiKey)
                .model("qwen-image-edit-max")
                .messages(Collections.singletonList(userMessage))
                .parameters(parameters)
                .build();

        MultiModalConversationResult result = conv.call(param);
        // 如需查看完整響應,請取消下行注釋
        // System.out.println(JsonUtils.toJson(result));
        List<Map<String, Object>> contentList = result.getOutput().getChoices().get(0).getMessage().getContent();
        int imageIndex = 1;
        for (Map<String, Object> content : contentList) {
            if (content.containsKey("image")) {
                System.out.println("輸出映像" + imageIndex + "的URL:" + content.get("image"));
                imageIndex++;
            }
        }
    }

    /**
     * 將檔案編碼為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) {
        try {
            call();
        } catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

通過URL下載映像

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class ImageDownloader {
    public static void downloadImage(String imageUrl, String savePath) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(300000);
            connection.setRequestMethod("GET");
            InputStream inputStream = connection.getInputStream();
            FileOutputStream outputStream = new FileOutputStream(savePath);
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();
            outputStream.close();
 
            System.out.println("映像已成功下載到: " + savePath);
        } catch (Exception e) {
            System.err.println("映像下載失敗: " + e.getMessage());
        }
    }
 
    public static void main(String[] args) {
        String imageUrl = "http://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxx?Expires=xxx";
        String savePath = "output.png";
        downloadImage(imageUrl, savePath);
    }
}

響應樣本

映像連結的有效期間為24小時,請及時下載映像。

{
    "requestId": "46281da9-9e02-941c-ac78-be88b8xxxxxx",
    "usage": {
        "image_count": 2,
        "width": 1024,
        "height": 1536
    },
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxx"
                        },
                        {
                            "image": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxx"
                        }
                    ]
                }
            }
        ]
    }
}

映像存取權限配置

模型產生的映像儲存於阿里雲OSS,每張映像會被分配一個OSS連結,如https://dashscope-result-xx.oss-cn-xxxx.aliyuncs.com/xxx.png。OSS連結允許公開訪問,可以使用此連結查看或者下載圖片,連結僅在 24 小時內有效。

如果您的業務對安全性要求較高,無法訪問阿里雲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:通義千問影像編輯模型支援哪些語言?

A:目前正式支援簡體中文和英文;其他語言可自行嘗試,但效果存在不確定性。

Q:上傳多張不同比例的參考圖時,輸出映像的比例以哪張為準?

A:預設情況下,輸出映像會以最後一張上傳的參考圖的比例為準。您也可以通過設定 parameters.size 參數來自訂輸出映像的尺寸。

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

A:模型的調用資訊存在小時級延遲,在模型調用完一小時後,請在模型觀測(新加坡北京頁面,查看調用量、調用次數、成功率等指標。詳情請參見賬單查詢與成本管理