通義千問-文生圖模型(Qwen-Image)是一款通用映像產生模型,支援多種藝術風格,尤其擅長複雜文本渲染。模型支援多行布局、段落級文本產生以及細粒度細節刻畫,可實現複雜的圖文混合布局設計。
快速入口:使用指南 | 線上體驗 | 技術部落格(更多效果展示) |
效果展示
輸入提示詞 | 輸出映像 |
Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere. |
|
前提條件
在調用前,您需要根據地區準備工作:擷取與配置 API Key,再配置API Key到環境變數(準備下線,併入配置 API Key)。
北京和新加坡地區擁有獨立的 API Key 與請求地址,不可混用,跨地區調用將導致鑒權失敗或服務報錯。
同步介面(推薦)
HTTP調用
通義千問Qwen-image模型支援同步介面,一次請求即可獲得結果,調用流程簡單,推薦用於多數情境。
新加坡地區: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
請求參數 | 文生圖 |
要求標頭(Headers) | |
Content-Type 請求內容類型。此參數必須設定為 | |
Authorization 請求身份認證。介面使用阿里雲百鍊API-Key進行身份認證。樣本值:Bearer sk-xxxx。 | |
請求體(Request Body) | |
model 模型名稱。可設定為 | |
input 輸入的基本資料。 | |
parameters 影像處理參數。 |
響應參數 | 任務執行成功任務資料(如任務狀態、映像URL等)僅保留24小時,逾時後會被自動清除。請您務必及時儲存產生的映像。 任務執行異常如果因為某種原因導致任務執行失敗,將返回相關資訊,可以通過code和message欄位明確指示錯誤原因。請參見錯誤資訊進行解決。 |
output 任務輸出資訊。 | |
usage 輸出資訊統計。只對成功的結果計數。 | |
request_id 請求唯一標識。可用於請求明細溯源和問題排查。 | |
code 請求失敗的錯誤碼。請求成功時不會返回此參數,詳情請參見錯誤資訊。 | |
message 請求失敗的詳細資料。請求成功時不會返回此參數,詳情請參見錯誤資訊。 |
DashScope SDK調用
DashScope SDK目前已支援Python和Java。
SDK與HTTP介面的參數名基本一致,參數結構根據語言特性進行封裝。同步調用參數說明可參考HTTP調用。
Python
請先確認已安裝最新版DashScope Python SDK,否則可能運行報錯:安裝SDK。
請求樣本
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'
messages = [
{
"role": "user",
"content": [
{"text": "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere."}
]
}
]
# 新加坡和北京地區的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")
response = MultiModalConversation.call(
api_key=api_key,
model="qwen-image-plus",
messages=messages,
result_format='message',
stream=False,
watermark=False,
prompt_extend=True,
negative_prompt='',
size='1328*1328'
)
if response.status_code == 200:
print(json.dumps(response, ensure_ascii=False))
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")響應樣本
映像連結的有效期間為24小時,請及時下載映像。
{
"status_code": 200,
"request_id": "d2d1a8c0-325f-9b9d-8b90-xxxxxx",
"code": "",
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png?Expires=xxx"
}
]
}
}
],
"task_metric": {
"TOTAL": 1,
"FAILED": 0,
"SUCCEEDED": 1
}
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"width": 1328,
"image_count": 1,
"height": 1328
}
}Java
請先確認已安裝最新版DashScope Java SDK,否則可能運行報錯:安裝SDK。
請求樣本
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;
public class QwenImage {
static {
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_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將下行替換為:static String apiKey="sk-xxx"
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void call() throws ApiException, NoApiKeyException, UploadFileException, IOException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("text", "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.")
)).build();
Map<String, Object> parameters = new HashMap<>();
parameters.put("watermark", false);
parameters.put("prompt_extend", true);
parameters.put("negative_prompt", "");
parameters.put("size", "1328*1328");
MultiModalConversationParam param = MultiModalConversationParam.builder()
.apiKey(apiKey)
.model("qwen-image-plus")
.messages(Collections.singletonList(userMessage))
.parameters(parameters)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
call();
} catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
響應樣本
映像連結的有效期間為24小時,請及時下載映像。
{
"requestId": "5b6f2d04-b019-40db-a5cc-xxxxxx",
"usage": {
"image_count": 1,
"width": 1328,
"height": 1328
},
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png?Expires=xxx"
}
]
}
}
]
}
}非同步介面(兩步擷取結果)
HTTP調用
通義千問Qwen-Image模型還支援非同步介面,其HTTP調用流程分為兩步:
建立任務擷取任務ID:發送一個請求建立任務,該請求會返回任務ID(task_id)。
根據任務ID查詢結果:使用task_id輪詢任務狀態,直到任務完成並獲得映像URL。
步驟1:建立任務擷取任務ID
新加坡地區:POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
北京地區:POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
建立成功後,使用介面返回的
task_id查詢結果,task_id 有效期間為 24 小時。請勿重複建立任務,輪詢擷取即可。
請求參數 | 文生圖 |
要求標頭(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://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id}
北京地區:GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}
輪詢建議:模型耗時約15秒。建議採用輪詢機制,並設定合理的查詢間隔(如3秒)來擷取結果。實際耗時受排隊任務數量和網路狀況影響,請您在擷取結果時耐心等待。
任務狀態流轉:PENDING(排隊中)→ RUNNING(處理中)→ SUCCEEDED(成功)/ FAILED(失敗)。
結果連結:任務成功後返回映像連結,有效期間為 24 小時。建議及時下載並轉存至儲存空間(如阿里雲 OSS)。
請求參數 | 查詢任務結果請將 新加坡和北京地區的API Key不同。準備工作:擷取與配置 API Key。 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為https://dashscope.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx |
要求標頭(Headers) | |
Authorization 請求身份認證。介面使用阿里雲百鍊API-Key進行身份認證。樣本值:Bearer sk-xxxx。 | |
URL路徑參數(Path parameters) | |
task_id 任務ID。 |
響應參數 | 任務執行成功任務資料(如任務狀態、映像URL等)僅保留24小時,逾時後會被自動清除。請您務必及時儲存產生的映像。 任務執行失敗若任務執行失敗,task_status將置為 FAILED,並提供錯誤碼和資訊。請參見錯誤資訊進行解決。 |
output 任務輸出資訊。 | |
usage 輸出資訊統計。只對成功的結果計數。 | |
request_id 請求唯一標識。可用於請求明細溯源和問題排查。 |
DashScope SDK調用
DashScope SDK目前已支援Python和Java。
SDK與HTTP介面的參數名基本一致,參數結構根據不同語言的SDK封裝而定。非同步呼叫參數說明可參考HTTP調用。
由於映像模型處理時間較長,底層服務採用非同步方式。SDK在此基礎上封裝了兩種調用模式:
同步調用(阻塞模式): SDK會自動等待任務完成,然後直接返回最終結果,調用體驗與常規同步調用一致。
非同步呼叫(非阻塞模式): 調用後將立即返回任務ID,需要使用者根據該ID自行查詢任務狀態和最終結果。
Python SDK調用
請先確認已安裝最新版DashScope Python SDK,否則可能運行報錯:安裝SDK。
同步調用
請求樣本
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
import dashscope
# 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
prompt = "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere."
# 新加坡和北京地區的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")
print('----sync call, please wait a moment----')
rsp = ImageSynthesis.call(api_key=api_key,
model="qwen-image-plus",
prompt=prompt,
n=1,
size='1328*1328',
prompt_extend=True,
watermark=False)
print(f'response: {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(f'sync_call Failed, status_code: {rsp.status_code}, code: {rsp.code}, message: {rsp.message}')
響應樣本
url 有效期間24小時,請及時下載映像。
{
"status_code": 200,
"request_id": "a47b1a65-7041-4565-9068-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "91093132-475e-43cf-b94e-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"url": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxxxxx",
"orig_prompt": "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.",
"actual_prompt": "Childhood-inspired hand-drawn poster design: Three playful puppies joyfully interact with a colorful ball on a vibrant patch of lush green grass. Delicate decorative elements including fluttering birds and twinkling stars are scattered throughout. At the top center, the bold, blue cartoon-style title “Come Play Ball!” stands out prominently. Directly beneath, the subtitle “Come [Show Off Your Skills]!” is rendered in cheerful green lettering. A whimsical speech bubble near one of the puppies contains the playful text: “Hehe, watch me amaze my little friends next!” At the bottom edge, smaller supplementary text reads: “We get to play ball with our friends again!” The color palette is centered on fresh greens and sky blues, accented with pops of bright pink and sunny yellow, enhancing the cheerful, childlike atmosphere. Style evokes nostalgic, hand-inked illustrations with soft textures, gentle linework, and a whimsical, storybook-like composition."
}
],
"submit_time": "2025-09-09 13:39:20.659",
"scheduled_time": "2025-09-09 13:39:20.717",
"end_time": "2025-09-09 13:39:45.233"
},
"usage": {
"image_count": 1
}
}非同步呼叫
請求樣本
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
import dashscope
import time
# 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'
prompt = "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere."
# 新加坡和北京地區的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")
def async_call():
print('----Creating Task----')
task_info = create_async_task()
print('----Polling Task Status----')
poll_task_status(task_info)
# Create asynchronous task
def create_async_task():
rsp = ImageSynthesis.async_call(api_key=api_key,
model="qwen-image-plus",
prompt=prompt,
n=1,
size='1328*1328',
prompt_extend=True,
watermark=False)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
else:
print(f'Failed to create task, status_code: {rsp.status_code}, code: {rsp.code}, message: {rsp.message}')
return rsp
# Poll asynchronous task status, query every 5 seconds, maximum polling for 1 minute
def poll_task_status(task):
start_time = time.time()
timeout = 60 # 1 minute timeout
while True:
# Check if timeout
if time.time() - start_time > timeout:
print('Polling timeout (1 minute), task not completed')
return
# Get task status
status_rsp = ImageSynthesis.fetch(task)
print(f'Task status query result: {status_rsp}')
if status_rsp.status_code != HTTPStatus.OK:
print(f'Failed to get task status, status_code: {status_rsp.status_code}, code: {status_rsp.code}, message: {status_rsp.message}')
return
task_status = status_rsp.output.task_status
print(f'Current task status: {task_status}')
if task_status == 'SUCCEEDED':
print('Task completed, downloading image...')
for result in status_rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open(f'./{file_name}', 'wb+') as f:
f.write(requests.get(result.url).content)
print(f'Image saved as: {file_name}')
break
elif task_status == 'FAILED':
print(f'Task execution failed, status: {task_status}, code: {status_rsp.code}, message: {status_rsp.message}')
break
elif task_status == 'PENDING' or task_status == 'RUNNING':
print('Task in progress, continue querying after 5 seconds...')
time.sleep(5)
else:
print(f'Unknown task status: {task_status}, continue querying after 5 seconds...')
time.sleep(5)
# Cancel asynchronous task, only tasks in PENDING status can be canceled
def cancel_task(task):
rsp = ImageSynthesis.cancel(task)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.task_status)
else:
print(f'Failed to cancel task, status_code: {rsp.status_code}, code: {rsp.code}, message: {rsp.message}')
if __name__ == '__main__':
async_call()
響應樣本
1、建立任務的響應樣本
{
"status_code": 200,
"request_id": "31b04171-011c-96bd-ac00-xxxxxx",
"code": "",
"message": "",
"output": {
"task_id": "4f90cf14-a34e-4eae-xxxxxxxx",
"task_status": "PENDING",
"results": []
},
"usage": null
}2、查詢任務結果的響應樣本
url 有效期間24小時,請及時下載映像。
{
"status_code": 200,
"request_id": "a47b1a65-7041-4565-9068-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "91093132-475e-43cf-b94e-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"url": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxxxxx",
"orig_prompt": "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.",
"actual_prompt": "Childhood-inspired hand-drawn poster design: Three playful puppies joyfully interact with a colorful ball on a vibrant patch of lush green grass. Delicate decorative elements including fluttering birds and twinkling stars are scattered throughout. At the top center, the bold, blue cartoon-style title “Come Play Ball!” stands out prominently. Directly beneath, the subtitle “Come [Show Off Your Skills]!” is rendered in cheerful green lettering. A whimsical speech bubble near one of the puppies contains the playful text: “Hehe, watch me amaze my little friends next!” At the bottom edge, smaller supplementary text reads: “We get to play ball with our friends again!” The color palette is centered on fresh greens and sky blues, accented with pops of bright pink and sunny yellow, enhancing the cheerful, childlike atmosphere. Style evokes nostalgic, hand-inked illustrations with soft textures, gentle linework, and a whimsical, storybook-like composition."
}
],
"submit_time": "2025-09-09 13:39:20.659",
"scheduled_time": "2025-09-09 13:39:20.717",
"end_time": "2025-09-09 13:39:45.233"
},
"usage": {
"image_count": 1
}
}Java SDK調用
請先確認已安裝最新版DashScope Java SDK,否則可能運行報錯:安裝SDK。
同步調用
請求樣本
// 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.HashMap;
import java.util.Map;
public class Text2Image {
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將下行替換為:static String apiKey = "sk-xxx"
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void basicCall() throws ApiException, NoApiKeyException {
String prompt = "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.";
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("qwen-image-plus")
.prompt(prompt)
.n(1)
.size("1328*1328")
.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));
}
public static void main(String[] args){
try{
basicCall();
}catch(ApiException|NoApiKeyException e){
System.out.println(e.getMessage());
}
}
}
響應樣本
url 有效期間24小時,請及時下載映像。
{
"request_id": "9f3044ba-528f-4606-8830-xxxxxx",
"output": {
"task_id": "fecf4c7f-3508-45f4-8454-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"orig_prompt": "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.",
"actual_prompt": "Childhood-inspired hand-drawn poster design: Three playful puppies joyfully interact with a colorful ball on a vibrant patch of lush green grass. Delicate decorative elements including fluttering birds and twinkling stars are scattered throughout. At the top center, the bold, blue cartoon-style title “Come Play Ball!” stands out prominently. Directly beneath, the subtitle “Come [Show Off Your Skills]!” is rendered in cheerful green lettering. A whimsical speech bubble near one of the puppies contains the playful text: “Hehe, watch me amaze my little friends next!” At the bottom edge, smaller supplementary text reads: “We get to play ball with our friends again!” The color palette is centered on fresh greens and sky blues, accented with pops of bright pink and sunny yellow, enhancing the cheerful, childlike atmosphere. Style evokes nostalgic, hand-inked illustrations with soft textures, gentle linework, and a whimsical, storybook-like composition.",
"url": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxxx"
}
]
},
"usage": {
"image_count": 1
}
}非同步呼叫
請求樣本
// 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.util.HashMap;
import java.util.Map;
public class Text2Image {
static {
// 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope.aliyuncs.com/api/v1";
}
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:static String apiKey = "sk-xxx"
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public void asyncCall() {
System.out.println("---Creating task----");
String taskId = this.createAsyncTask();
System.out.println("--Waiting for task to complete and return image url----");
this.waitAsyncTask(taskId);
}
public String createAsyncTask() {
String prompt = "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.";
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("qwen-image-plus")
.prompt(prompt)
.n(1)
.size("1328*1328")
.parameters(parameters)
.build();
try {
ImageSynthesisResult result = new ImageSynthesis().asyncCall(param);
System.out.println(JsonUtils.toJson(result));
String taskId = result.getOutput().getTaskId();
System.out.println("task_id=" + taskId);
return taskId;
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public void waitAsyncTask(String taskId) {
ImageSynthesis imageSynthesis = new ImageSynthesis();
long startTime = System.currentTimeMillis();
int timeout = 60 * 1000; // 1 minute timeout
int interval = 5 * 1000; // 5 second polling interval
while (true) {
if (System.currentTimeMillis() - startTime > timeout) {
System.out.println("Polling timed out (1 minute), task not completed");
return;
}
try {
ImageSynthesisResult result = imageSynthesis.fetch(taskId, apiKey);
System.out.println("Task status query result: " + JsonUtils.toJson(result));
if (result.getOutput() == null) {
System.out.println("Failed to get task status, output is empty");
return;
}
String taskStatus = result.getOutput().getTaskStatus();
System.out.println("Current task status: " + taskStatus);
switch (taskStatus) {
case "SUCCEEDED":
System.out.println("Task completed");
System.out.println(JsonUtils.toJson(result));
return;
case "FAILED":
System.out.println("Task execution failed, status: " + taskStatus);
return;
case "PENDING":
case "RUNNING":
System.out.println("Task in progress, querying again in 5 seconds...");
Thread.sleep(interval);
break;
default:
System.out.println("Unknown task status: " + taskStatus + ", querying again in 5 seconds...");
Thread.sleep(interval);
break;
}
} catch (ApiException | NoApiKeyException e) {
System.err.println("API call exception: " + e.getMessage());
return;
} catch (InterruptedException e) {
System.err.println("Thread interruption exception: " + e.getMessage());
Thread.currentThread().interrupt();
return;
}
}
}
public static void main(String[] args){
Text2Image text2Image = new Text2Image();
text2Image.asyncCall();
}
}響應樣本
1、建立任務的響應樣本
{
"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
"output": {
"task_id": "7277e20e-aa01-4709-xxxxxxxx",
"task_status": "PENDING"
}
}2、查詢任務結果的響應樣本
url 有效期間24小時,請及時下載映像。
{
"request_id": "9f3044ba-528f-4606-8830-xxxxxx",
"output": {
"task_id": "fecf4c7f-3508-45f4-8454-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"orig_prompt": "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.",
"actual_prompt": "Childhood-inspired hand-drawn poster design: Three playful puppies joyfully interact with a colorful ball on a vibrant patch of lush green grass. Delicate decorative elements including fluttering birds and twinkling stars are scattered throughout. At the top center, the bold, blue cartoon-style title “Come Play Ball!” stands out prominently. Directly beneath, the subtitle “Come [Show Off Your Skills]!” is rendered in cheerful green lettering. A whimsical speech bubble near one of the puppies contains the playful text: “Hehe, watch me amaze my little friends next!” At the bottom edge, smaller supplementary text reads: “We get to play ball with our friends again!” The color palette is centered on fresh greens and sky blues, accented with pops of bright pink and sunny yellow, enhancing the cheerful, childlike atmosphere. Style evokes nostalgic, hand-inked illustrations with soft textures, gentle linework, and a whimsical, storybook-like composition.",
"url": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxxx"
}
]
},
"usage": {
"image_count": 1
}
}計費與限流
當前qwen-image-plus與qwen-image能力相同,但qwen-image-plus價格更優惠,推薦使用。
新加坡地區
模型名稱 | 單價 | 限流(主帳號與RAM子帳號共用) | 免費額度 | |
任務下發介面RPS限制 | 同時處理中任務數量 | |||
qwen-image-plus | $0.03/張 | 2 | 2 | 免費額度:各100張 有效期間:阿里雲百鍊開通後90天內 |
qwen-image | $0.035/張 | 2 | 2 | |
北京地區
模型名稱 | 單價 | 限流(主帳號與RAM子帳號共用) | 免費額度 | |
任務下發介面RPS限制 | 同時處理中任務數量 | |||
qwen-image-plus | $0.028671/張 | 2 | 2 | 無免費額度 |
qwen-image | $0.035/張 | 2 | 2 | |
計費規則
計費項目:按成功產生的 映像張數 計費,採用按量後付費模式。
計費公式:費用 = 計費單價 × 映像張數。
抵扣順序:優先消耗免費額度。額度用盡後,預設轉為隨用隨付。
您可開啟“免費額度用完即停”功能,以避免免費額度耗盡後產生額外費用。詳情請參見免費額度。
失敗不計費:模型調用失敗或處理錯誤不產生任何費用,也不消耗免費額度。
免費額度
關於免費額度的領取、查詢、使用方法等詳情,請參見免費額度。
調用量查詢
模型調用完約一小時後,請在模型觀測(新加坡)頁面,查看調用量、調用次數、成功率等指標。
如果使用“華北2(北京)”地區的模型,請前往“華北2(北京)”地區的模型觀測頁面。
限流
模型限流規則及常見問題,請參見限流。
映像訪問配置
模型產生的映像儲存於阿里雲OSS,每張映像會被分配一個OSS連結,如https://dashscope-result-xx.oss-cn-xxxx.aliyuncs.com/xxx.png。OSS連結允許公開訪問,您可以使用此連結查看或者下載圖片,連結僅在 24 小時內有效。
特別注意的是,如果您的業務對安全性要求較高,無法訪問阿里雲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:prompt_extend參數應該開啟還是關閉?
A: 當輸入的prompt比較簡潔或希望模型發揮更多創意時,建議保持開啟(預設)。當prompt已經非常詳細、專業,或對API響應延遲有嚴格要求時,建議顯式設定為false。
Q:qwen-image、qwen-image-plus、qwen-image-edit 等模型的區別是什嗎?
A:
文生圖模型:
qwen-image與qwen-image-plus
根據文本描述產生映像。當前兩者能力相同,但qwen-image-plus的價格更優惠,推薦使用。影像編輯模型:
qwen-image-edit
根據輸入的映像和文本指令,執行圖生圖、局部修改等操作,詳情請參見通義千問-影像編輯。
