通過文生圖API,您可以基於文本描述創造出全新的映像。阿里雲百鍊提供兩大系列模型:
千問(Qwen-Image): 擅長渲染複雜的中英文文本。
萬相(Wan系列): 用於產生寫實映像和攝影級視覺效果。
模型效果
千問(Qwen-image)
複雜文字
| 超長段落
| 複雜布局
|
海報製作
| 插畫設計
| 寫實攝影
|
萬相
人像寫真
| 寫實攝影
| 繪畫流派
|
文字產生
| 海報設計
| 組圖產生
|
支援的模型
模型選型
複雜文字渲染(如海報、對聯):首選
qwen-image-2.0-pro、wan2.6-t2i。寫實情境和攝影風格(通用情境):可選萬相模型,如
wan2.6-t2i、wan2.5-t2i-preview。需要自訂輸出映像解析度:推薦
qwen-image-2.0系列或萬相模型。qwen-image-2.0系列支援自由設定寬高,輸出映像總像素在[512*512, 2048*2048]之間;萬相模型如wan2.6-t2i,輸出映像總像素在[1280*1280, 1440*1440]之間。qwen-image-max、qwen-image-plus系列模型僅支援5種固定尺寸:1664*928(16:9)、928*1664(9:16)、1328*1328(1:1)、1472*1104(4:3)、1104*1472(3:4)。
快速開始
前提條件
在調用前,請擷取API Key,再配置API Key到環境變數(準備下線,併入配置 API Key)。如果通過DashScope SDK進行調用,還需要安裝SDK。
範例程式碼
調用方式說明:
千問文生圖模型均支援同步調用,其中qwen-image-plus、qwen-image模型支援非同步呼叫,詳情請參見千問-文生圖。
萬相文生圖模型均支援非同步呼叫,其中wan2.6-t2i支援同步調用,詳情請參見萬相-文生圖V2。
同步調用
Python
請求樣本
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-2.0-pro",
messages=messages,
result_format='message',
stream=False,
watermark=False,
prompt_extend=True,
negative_prompt="低解析度,低畫質,肢體畸形,手指畸形,畫面過飽和,蠟像感,人臉無細節,過度光滑,畫面具有AI感。構圖混亂。文字模糊,扭曲。",
size='2048*2048'
)
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"
}
]
}
}
]
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"width": 2048,
"image_count": 1,
"height": 2048
}
}Java
請求樣本
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", "低解析度,低畫質,肢體畸形,手指畸形,畫面過飽和,蠟像感,人臉無細節,過度光滑,畫面具有AI感。構圖混亂。文字模糊,扭曲。");
parameters.put("size", "2048*2048");
MultiModalConversationParam param = MultiModalConversationParam.builder()
.apiKey(apiKey)
.model("qwen-image-2.0-pro")
.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": 2048,
"height": 2048
},
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png?Expires=xxx"
}
]
}
}
]
}
}curl
請求樣本
curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
"model": "qwen-image-2.0-pro",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"text": "冬日北京的都市街景,青灰瓦頂、硃紅色外牆的兩間相鄰中式商鋪比肩而立,簷下懸掛印有剪紙馬的暖光燈籠,在陰天漫射光中投下柔和光暈,映照濕潤鵝卵石路面泛起細膩反光。左側為書法店:靛藍色老舊的牌匾上以遒勁行書刻著“文字渲染”。店門口的玻璃上掛著一幅字,自上而下,用田英章硬筆寫著“專業投影片 中英文海報 進階資訊圖”,落款印章為“1k token”硃砂印。店內的牆上,可以模糊的辨認有三幅豎排的書法作品,第一幅寫著著“阿里巴巴”,第二幅寫著“通義千問”,第三福寫著“映像產生”。一位白髮蒼蒼的老人背對著鏡頭觀賞。右側為花店,牌匾上以鮮花做成文字“真實質感”;店內多層花架陳列紅玫瑰、粉洋牡丹和綠植,門上貼了一個圓形花邊標識,標識上寫著“2k resolution”,門口擺放了一個彩色霓虹燈,上面寫著“細膩刻畫 人物 自然 建築”。兩家店中間堆放了一個雪人,舉了一老式小黑板,上面用粉筆字寫著“Qwen-Image-2.0 正式發布”。街道左側,年輕情侶依偎在一起,女孩是瘦臉,身穿米白色羊絨大衣,肉色光腿神器。女孩舉著心形透明氣球,氣球印有白色的字:“生圖編輯變形平板”。裡面有一個毛茸茸的卡皮巴拉玩偶。男孩身著剪裁合體的深灰色呢子外套,內搭淺色高領毛衣。街道右側,一個後背上寫著“更小模型,更快速度”的騎手疾馳而過。整條街光影交織、動靜相宜。"
}
]
}
]
},
"parameters": {
"negative_prompt": "低解析度,低畫質,肢體畸形,手指畸形,畫面過飽和,蠟像感,人臉無細節,過度光滑,畫面具有AI感。構圖混亂。文字模糊,扭曲。",
"prompt_extend": true,
"watermark": false,
"size": "2048*2048"
}
}'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-2.0-pro",
"input": {
"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."
}
]
}
]
},
"parameters": {
"negative_prompt": "低解析度,低畫質,肢體畸形,手指畸形,畫面過飽和,蠟像感,人臉無細節,過度光滑,畫面具有AI感。構圖混亂。文字模糊,扭曲。",
"prompt_extend": true,
"watermark": false,
"size": "2048*2048"
}
}'響應樣本
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"content": [
{
"image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"
}
],
"role": "assistant"
}
}
]
},
"usage": {
"height": 2048,
"image_count": 1,
"width": 2048
},
"request_id": "d0250a3d-b07f-49e1-bdc8-6793f4929xxx"
}非同步呼叫
SDK 在底層封裝了非同步處理邏輯,上層介面表現為同步調用(即單次請求並等待最終結果返回);而 curl 樣本則對應兩個獨立的非同步 API 介面:一個用於提交任務,另一個用於查詢結果。
Python
請求樣本
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
# 以下為新加坡地區base_url,各地區的base_url不同
dashscope.base_http_api_url = 'https://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")
message = Message(
role="user",
content=[
{
'text': '一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵'
}
]
)
print("----sync call, please wait a moment----")
rsp = ImageGeneration.call(
model="wan2.6-t2i",
api_key=api_key,
messages=[message],
negative_prompt="",
prompt_extend=True,
watermark=False,
n=1,
size="1280*1280"
)
print(rsp)
響應樣本
url 有效期間24小時,請及時下載映像。
{
"status_code": 200,
"request_id": "820dd0db-eb42-4e05-8d6a-1ddb4axxxxxx",
"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": 0,
"output_tokens": 0,
"characters": 0,
"image_count": 1,
"size": "1280*1280",
"total_tokens": 0
}
}
Java
請求樣本
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.util.Collections;
public class Main {
static {
// 以下為新加坡地區url,各地區的base_url不同
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");
public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException {
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Collections.singletonList(
Collections.singletonMap("text", "一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵")
)).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.6-t2i")
.n(1)
.size("1280*1280")
.negativePrompt("")
.promptExtend(true)
.watermark(false)
.messages(Collections.singletonList(message))
.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());
}
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
basicCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
}
}
響應樣本
url 有效期間24小時,請及時下載映像。
{
"status_code": 200,
"request_id": "50b57166-eaaa-4f17-b1e0-35a5ca88672c",
"code": "",
"message": "",
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
"type": "image"
}
]
}
}
],
"finished": true
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"image_count": 1,
"size": "1280*1280",
"total_tokens": 0
}
}
curl
非同步呼叫必須設定 Header 參數
X-DashScope-Async為enable。非同步任務的
task_id查詢有效期間為 24 小時,到期後任務狀態將變為UNKNOWN。
步驟1:發起建立工作要求
該請求會返回一個任務ID(task_id)。
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'X-DashScope-Async: enable' \
--data '{
"model": "wan2.6-t2i",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"text": "一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵"
}
]
}
]
},
"parameters": {
"prompt_extend": true,
"watermark": false,
"n": 1,
"negative_prompt": "",
"size": "1280*1280"
}
}'步驟2:根據任務ID查詢結果
使用上一步擷取的 task_id,通過介面輪詢任務狀態,直到 task_status 變為 SUCCEEDED 或 FAILED。
將{task_id}完整替換為上一步介面返回的task_id的值。task_id查詢有效期間為24小時。
curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"關鍵能力
1. 指令遵循(提示詞)
參數:input.prompt(必選)、input.negative_prompt(可選)。
prompt(正向提示詞):描述希望在畫面中看到的內容、主體、情境、風格、光照和構圖。文生圖的核心控制參數。
negative_prompt(反向提示詞):描述不希望在畫面中出現的內容,如“模糊”、“多餘的手指”等。僅用於輔助最佳化產生品質。
撰寫技巧:一個結構化的 Prompt 通常能帶來更好的效果,撰寫技巧請參見文生圖Prompt指南。
2. 開啟prompt智能改寫
參數: parameters.prompt_extend (bool, 預設為 true)。
此功能可自動擴充和最佳化較短的Prompt,提升出圖效果。開啟此功能額外耗時 3-5 秒。此耗時為使用大模型改寫文本。
實踐建議:
建議開啟:當輸入 Prompt 較簡潔或寬泛時,此功能可顯著增益圖像效果。
建議關閉:若需控制畫面細節、或已提供詳細描述,或對響應延遲敏感。請將參數
prompt_extend顯式設為false。
3. 設定輸出映像解析度
參數: parameters.size (string),格式為 "寬*高"。
qwen-image-2.0 系列:支援自由設定寬高,輸出映像總像素需在512*512至2048*2048之間。預設解析度為2048*2048。推薦解析度:
2688*1536:16:91536*2688:9:162048*2048(預設值):1:12368*1728:4:31728*2368:3:4
qwen-image-max、qwen-image-plus 系列:僅支援以下 5 種固定的解析度:
1664*928(預設值):16:91472*1104:4:31328*1328:1:11104*1472:3:4928*1664:9:16
萬相 V2 版模型 (2.0 及以上版本):支援在 [512, 1440] 像素範圍內任意組合寬高,總像素不超過 1440*1440。常用解析度:
1024*1024(預設值):1:11440*810: 16:9810*1440: 9:161440*1080: 4:31080*1440: 3:4
應用於生產環境
容錯策略
處理限流:當 API 返回
Throttling錯誤碼或 HTTP 429 狀態代碼時,表明已觸發限流,限流處理請參見限流。非同步任務輪詢:輪詢查詢非同步任務結果時,建議採用合理的輪詢策略(如前30秒每3秒一次,之後拉長間隔),避免因過於頻繁的請求而觸發限流。為任務設定一個最終逾時時間(如 2 分鐘),逾時後標記為失敗。
風險防範
結果持久化:API 返回的圖片 URL 有 24 小時有效期間。生產系統必須在擷取 URL 後立即下載圖片,並轉存至您自己的持久化儲存服務中(如阿里雲Object Storage Service)。
Alibaba Content Security Service審核:所有
prompt和negative_prompt都會經過Alibaba Content Security Service審核。若輸入內容不合規,請求將被攔截並返回DataInspectionFailed錯誤。產生內容的著作權與合規風險:請確保您的提示詞內容符合相關法律法規。產生包含品牌商標、名人肖像、受著作權保護的 IP 形象等內容可能涉及侵權風險,請您自行評估並承擔相應責任。
API文檔
計費與限流
錯誤碼
如果模型調用失敗並返回報錯資訊,請參見錯誤資訊進行解決。
常見問題
Q: 圖片 URL 多久會失效?我應該如何永久儲存圖片?
A: 圖片 URL 的有效期間為 24 小時。您必須在擷取到 URL 後,立即通過程式下載圖片,並將其儲存到您自己的持久化儲存中,例如本機伺服器或阿里雲Object Storage Service。
Q: 調用API返回DataInspectionFailed錯誤,如何處理?
A: 該錯誤表示輸入文本觸發了Alibaba Content Security Service審核。請檢查並修改prompt或negative_prompt中的文本,移除可能違規的內容後重試。
Q: prompt_extend參數應該開啟還是關閉?
A: 當輸入的prompt比較簡潔或希望模型發揮更多創意時,建議保持開啟(預設)。當prompt已經非常詳細、專業,或對API響應延遲有嚴格要求時,建議顯式設定為false。
Q: 如何增益圖像中文字的產生效果?
A: 推薦使用qwen-image-2.0-pro模型,它具備更專業的文字渲染能力。











