通义千问-文生图模型(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 与请求地址,不可混用,跨地域调用将导致鉴权失败或服务报错。
同步接口(推荐)
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
根据输入的图像和文本指令,执行图生图、局部修改等操作,详情请参见通义千问-图像编辑。
