O Qwen-Image é um modelo de geração de imagens de uso geral que oferece suporte a diversos estilos artísticos e se destaca na renderização complexa de texto . Ele processa layouts com várias linhas, gera textos no nível de parágrafo e renderiza detalhes refinados.
Acesso rápido: Guia do usuário | Experimente online(Singapore | Beijing)** |
Exemplos
Prompt | Imagem gerada |
|---|---|
Um pôster desenhado à mão em estilo terapêutico, mostrando três filhotes brincando com uma bola sobre uma grama verde exuberante, adornado com elementos decorativos como pássaros e estrelas. O título principal “Venha Brincar de Bola!” aparece em destaque no topo, com uma fonte cartoon azul e em negrito. Abaixo dele, o subtítulo “Venha [Mostrar Suas Habilidades]!” surge em fonte verde. Um balão de fala adiciona um charme lúdico com o texto: “Hehe, veja só como vou impressionar meus amiguinhos agora!” Na parte inferior, um texto complementar diz: “Que bom jogar bola com nossos amigos de novo!” A paleta de cores gira em torno de verdes e azuis frescos, com toques de rosa e amarelo vibrantes para ressaltar uma atmosfera alegre e infantil. |
|
Visão geral do modelo
| Modelo | Descrição | Especificações da imagem de saída |
|---|---|---|
qwen-image-2.0-pro
| Série Qwen Pro para geração e edição de imagens. Oferece renderização de texto mais robusta, textura realista e maior aderência semântica.
| Resolução: Defina largura e altura livremente. O total de pixels deve ficar entre 512×512 e 2048×2048. A resolução padrão é 2048×2048. Formato: PNG Número de imagens: 1–6 |
qwen-image-2.0-pro-2026-06-22 | ||
qwen-image-2.0-pro-2026-04-22 | ||
qwen-image-2.0-pro-2026-03-03 | ||
qwen-image-2.0
| Série acelerada Qwen para geração e edição de imagens. Equilibra qualidade e velocidade de resposta.
| |
qwen-image-2.0-2026-03-03 | ||
qwen-image-max
| Série Qwen Max para geração de imagens. Proporciona maior realismo e naturalidade, com menos artefatos de geração por IA. | Resolução: Consulte as configurações do parâmetro size para ver as resoluções e proporções suportadas. Formato: PNG Número de imagens: Fixo em 1 |
qwen-image-max-2025-12-30 | ||
qwen-image-plus
| Série Qwen Plus para geração de imagens. Destaca-se pela variedade de estilos artísticos e pela renderização de texto. | |
qwen-image-plus-2026-01-09 | ||
qwen-image |
Apenas o qwen-image-plus e o qwen-image oferecem suporte a chamadas assíncronas .
ObservaçãoAntes de chamar a API, verifique a lista de modelos suportados para sua região.
Pré-requisitos
Antes de fazer uma chamada, obtenha uma chave de API e exporte a chave de API como uma variável de ambiente. Para realizar chamadas com o SDK, instale o DashScope SDK.
ImportanteAs regiões China (Beijing) e Singapore possuem chaves de API e endpoints de solicitação separados. Não é possível usá-las de forma intercambiável. Chamadas entre regiões causam falhas de autenticação ou erros de service.
API síncrona (recomendada)
HTTP
Chamadas síncronas retornam os resultados em uma única requisição.
Singapore: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
China (Beijing): POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
Substitua {WorkspaceId} pelo seu ID do workspace real.
Parâmetros da requisição | Text-to-image |
Cabeçalhos da requisição | |
Content-Type O tipo de conteúdo da requisição. Deve ser | |
Authorization Autentica a requisição com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx. | |
Corpo da requisição | |
model Nome do modelo. Exemplo: | |
input Informações de entrada. | |
parameters Parâmetros de processamento de imagem. |
Parâmetros da resposta | Tarefa concluída com sucessoAs URLs das imagens são válidas apenas por 24 horas e depois são removidas automaticamente. Salve as imagens geradas prontamente. Falha na tarefaSe a tarefa falhar, a resposta inclui detalhes do erro nos campos code e message. Consulte Códigos de erro. |
output Informações de saída da tarefa. | |
usage ObservaçãoEste campo é retornado apenas em chamadas assíncronas. Chamadas síncronas do SDK ImageSynthesis não retornam este campo. Estatísticas de saída. Conta apenas resultados bem-sucedidos. | |
request_id Identificador único da requisição para rastreamento e solução de problemas. | |
code Código de erro. Retornado apenas para requisições com falha. Consulte Códigos de erro. | |
message Mensagem de erro detalhada. Retornada apenas para requisições com falha. Consulte Códigos de erro. |
Chamada via DashScope SDK
O DashScope SDK suporta Python e Java.
Os nomes dos parâmetros no SDK correspondem closely aos parâmetros HTTP, e as estruturas dos parâmetros seguem convenções específicas da linguagem. Para parâmetros de chamada síncrona, consulte HTTP.
Python
ObservaçãoInstale a versão mais recente do DashScope Python SDK para evitar erros de execução: Instalar SDK.
Exemplo de requisição
import json
import os
import dashscope
from dashscope import MultiModalConversation
# Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.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 keys differ between Beijing and Singapore regions. Get your API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# If you haven't set the environment variable, replace the line below with: 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="Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.",
size='2048*2048'
)
if response.status_code == 200:
print(json.dumps(response, ensure_ascii=False))
else:
print(f"HTTP status code: {response.status_code}")
print(f"Error code: {response.code}")
print(f"Error message: {response.message}")
print("See documentation: https://www.alibabacloud.com/help/en/model-studio/error-code")
Exemplo de resposta
As URLs das imagens expiram após 24 horas. Baixe as imagens prontamente.
{
"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"
}
]
}
}
]
}
}
Java
ObservaçãoÉ obrigatório instalar a versão mais recente do DashScope Java SDK. Caso contrário, erros de tempo de execução podem ocorrer: Instalar SDK.
Exemplo de solicitação
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 {
// Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// API keys differ between Beijing and Singapore regions. Get your API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
// If you haven't set the environment variable, replace the line below with: 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", "Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.");
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);
}
}
Exemplo de resposta
As URLs das imagens expiram após 24 horas. Baixe as imagens prontamente.
{
"requestId": "5b6f2d04-b019-40db-a5cc-xxxxxx",
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png?Expires=xxx"
}
]
}
}
]
}
}
API assíncrona
ImportanteApenas os modelos qwen-image-plus e qwen-image suportam chamadas assíncronas.
HTTP
Chamadas assíncronas utilizam um fluxo de trabalho HTTP em duas etapas:
- Crie uma tarefa para obter um ID de tarefa: Envie uma solicitação para criar uma tarefa. A resposta retorna um ID de tarefa (task_id).
- Consulte os resultados usando o ID da tarefa: Consulte o status da tarefa com o task_id até que ela seja concluída e retorne uma URL de imagem.
Etapa 1: Criar uma tarefa para obter um ID de tarefa
Singapore: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
China (Beijing): POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
Observação
- Após a criação da tarefa, utilize o
task_idretornado para consultar o resultado. Otask_idpermanece válido por 24 horas. Não crie tarefas duplicadas. Em vez disso, use consultas periódicas para recuperar o resultado. - Para orientações destinadas a iniciantes, consulte Chamar APIs com Postman ou cURL.
Parâmetros da solicitação | Texto para imagemApenas |
Cabeçalhos da solicitação | |
Content-Type O tipo de conteúdo da solicitação. Deve ser | |
Authorization Autentica a solicitação com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx. | |
X-DashScope-Async Ativa o processamento assíncrono. Solicitações HTTP suportam apenas chamadas assíncronas. O valor deve ser ImportanteSe este cabeçalho de solicitação estiver ausente, o erro "current user api does not support synchronous calls" será retornado. | |
Corpo da solicitação | |
model Nome do modelo. Apenas Exemplo: | |
input Informações de entrada. | |
parameters Parâmetros de processamento de imagem. |
Parâmetros da resposta | Resposta bem-sucedidaSalve o Resposta de erroFalha na criação da tarefa. Consulte Códigos de erro. |
output Informações de saída da tarefa. | |
request_id Identificador único da solicitação para rastreamento e solução de problemas. | |
code Código de erro. Retornado apenas para solicitações com falha. Consulte Códigos de erro. | |
message Mensagem de erro detalhada. Retornada apenas para solicitações com falha. Consulte Códigos de erro. |
Etapa 2: Consultar resultados usando o ID da tarefa
China (Beijing)
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do workspace real.
Singapore
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do workspace real.
Singapore
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do workspace real.
China (Beijing)
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do workspace real.
Observação
- Recomendação de consulta: A geração de imagens demanda tempo. Utilize um mecanismo de consulta periódica com intervalo razoável, como 10 segundos.
- Transição de estado da tarefa: PENDING → RUNNING → SUCCEEDED ou FAILED.
- Link do resultado: Após o sucesso da tarefa, uma URL de imagem válida por 24 horas é retornada. Baixe e salve a imagem em armazenamento permanente, como o OSS.
Parâmetros da solicitação | Consultar resultados da tarefaSubstitua |
Cabeçalhos da solicitação | |
Authorization Autentica a solicitação com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx. | |
Parâmetros de caminho da URL | |
task_id O ID da tarefa. |
Parâmetros de resposta | Tarefa bem-sucedidaOs dados da tarefa (status e URLs das imagens) são retidos por apenas 24 horas e depois removidos automaticamente. Salve as imagens geradas imediatamente. Falha na tarefaQuando uma tarefa falha, o |
output Informações de saída da tarefa. | |
usage Estatísticas de saída. Conta apenas resultados bem-sucedidos. | |
request_id Identificador exclusivo da solicitação para rastreamento e solução de problemas. |
DashScope SDK
O DashScope SDK oferece suporte a Python e Java.
Os nomes dos parâmetros do SDK correspondem estreitamente aos seus equivalentes HTTP. As estruturas dos parâmetros seguem as convenções específicas de cada linguagem. Para parâmetros de chamadas assíncronas, consulte HTTP.
Modelos de imagem exigem tempos de processamento mais longos, portanto o service subjacente utiliza execução assíncrona. O SDK fornece dois modos:
- Chamada síncrona (modo de bloqueio): O SDK aguarda a conclusão da tarefa e retorna o resultado final. Este comportamento corresponde ao padrão de chamadas síncronas.
- Chamada assíncrona (modo sem bloqueio): A chamada retorna imediatamente com um ID de tarefa. Utilize esse ID para consultar o status e obter o resultado final.
SDK Python
ObservaçãoInstale a versão mais recente do DashScope Python SDK para evitar erros de tempo de execução: Instalar SDK.
Synchronous
Exemplo de solicitação
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
import dashscope
# Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.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 keys differ between Beijing and Singapore regions. Get your API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# If you haven't set the environment variable, replace the line below with: 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", # Only qwen-image-plus and qwen-image support asynchronous calls
prompt=prompt,
negative_prompt=" ",
n=1,
size='1664*928',
prompt_extend=True,
watermark=False)
print(f'response: {rsp}')
if rsp.status_code == HTTPStatus.OK:
# Save image in current directory
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(result.url).content)
else:
print(f'Sync call failed, status_code: {rsp.status_code}, code: {rsp.code}, message: {rsp.message}')
Exemplo de resposta
As URLs expiram após 24 horas. Baixe as imagens prontamente.
{
"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
}
}
Asynchronous
Exemplo de solicitação
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
# Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.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 keys differ between Beijing and Singapore regions. Get your API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# If you haven't set the environment variable, replace the line below with: 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", # Only qwen-image-plus and qwen-image support asynchronous calls
prompt=prompt,
negative_prompt=" ",
n=1,
size='1664*928',
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()
Exemplo de resposta
- Resposta para criação de tarefa
{
"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
}
-
Resposta para consulta de resultados da tarefa
As URLs expiram após 24 horas. Baixe as imagens prontamente.
{
"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
}
}
SDK Java
ObservaçãoÉ necessário instalar a versão mais recente do DashScope Java SDK. Caso contrário, podem ocorrer erros de tempo de execução: Instalar SDK.
Synchronous
Exemplo de solicitação
// 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 {
// Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// API keys differ between Beijing and Singapore regions. Get your API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
// If you haven't set the environment variable, replace the line below with: 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);
parameters.put("negative_prompt", " ");
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
// Only qwen-image-plus and qwen-image support asynchronous calls
.model("qwen-image-plus")
.prompt(prompt)
.n(1)
.size("1664*928")
.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());
}
}
}
Exemplo de resposta
As URLs expiram após 24 horas. Baixe as imagens prontamente.
{
"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
}
}
Assíncrono
Exemplo de solicitação
// 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 {
// Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// API keys differ between Beijing and Singapore regions. Get your API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
// If you haven't set the environment variable, replace the line below with: 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);
parameters.put("negative_prompt", " ");
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
// Only qwen-image-plus and qwen-image support asynchronous calls
.model("qwen-image-plus")
.prompt(prompt)
.n(1)
.size("1664*928")
.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();
}
}
Exemplo de resposta
- Resposta da criação da tarefa
{
"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
"output": {
"task_id": "7277e20e-aa01-4709-xxxxxxxx",
"task_status": "PENDING"
}
}
-
Resposta da consulta dos resultados da tarefa
As URLs expiram após 24 horas. Baixe as imagens prontamente.
{
"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
}
}
Uso com o OpenAI Agents SDK
Modelos de geração de imagens como o Qwen-Image são chamados por meio da API nativa do DashScope e não suportam o modo compatível com OpenAI (compatible-mode). Portanto, não é possível usá-los diretamente como modelo de raciocínio de um Agent no OpenAI Agents SDK.
Em frameworks de agentes como o OpenAI Agents SDK, você pode encapsular a geração de imagens como uma ferramenta (function tool) e utilizar um modelo de chat de texto compatível com o modo OpenAI (como o qwen-plus) como núcleo de raciocínio do Agent para orquestrá-la. Por exemplo:
Antes de executar, instale as dependências: pip install openai-agents dashscope.
import os
import asyncio
import dashscope
from openai import AsyncOpenAI
from dashscope import MultiModalConversation
from agents import Agent, Runner, function_tool, OpenAIChatCompletionsModel
# Read the Model Studio API Key from an environment variable
# (or replace with api_key="sk-xxx")
API_KEY = os.getenv("DASHSCOPE_API_KEY")
# Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# The text chat model (the Agent's reasoning core) is accessed via OpenAI-compatible mode
client = AsyncOpenAI(api_key=API_KEY, base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1")
# Wrap image generation as a function tool for the Agent to call
@function_tool
def generate_image(prompt: str) -> str:
"""Generate an image from a text description and return its URL. prompt: the text description of the image."""
rsp = MultiModalConversation.call(
api_key=API_KEY,
model="qwen-image",
messages=[{"role": "user", "content": [{"text": prompt}]}],
result_format="message",
)
if rsp.status_code != 200:
return f"Generation failed: {rsp.code} {rsp.message}"
return rsp.output.choices[0].message.content[0]["image"]
agent = Agent(
name="Image Assistant",
instructions="You are an image generation assistant. When the user wants an image, call the generate_image tool and return the image URL to the user.",
model=OpenAIChatCompletionsModel(model="qwen-plus", openai_client=client),
tools=[generate_image],
)
async def main():
result = await Runner.run(agent, "Draw a corgi running on the grass")
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
Faturamento e limitação de taxa
- Para cotas gratuitas e preços, consulte Preços dos modelos.
- Para limites de taxa, consulte Qwen-Image.
- Detalhes do faturamento: Cada imagem gerada com sucesso é cobrada. Chamadas com falha ou erros de processamento não geram cobranças nem consomem sua cota gratuita para novos usuários.
Códigos de erro
Se a chamada do modelo falhar e retornar uma mensagem de erro, consulte Códigos de erro para resolução.
Perguntas frequentes
P: Devo ativar ou desativar o parâmetro prompt_extend?
R: Ative esta opção (padrão) se desejar um conteúdo de imagem mais diversificado e permitir que o modelo adicione detalhes. Desative-a caso precise de controle mais rigoroso sobre os detalhes da imagem e otimize seus prompts usando o Guia de prompts de texto para imagem.
P: Quais são as diferenças entre qwen-image, qwen-image-plus, qwen-image-max, qwen-image-2.0 e qwen-image-edit?
R:
-
Modelos combinados de geração e edição de imagens: Suportam tanto texto para imagem quanto edição de imagens.
qwen-image-2.0-proeqwen-image-2.0-pro-2026-03-03: Mesmas capacidades. A série Pro oferece renderização de texto mais profissional, texturas realistas mais refinadas, cenas realistas detalhadas e maior aderência semântica. Suporta apenas chamadas síncronas.qwen-image-2.0eqwen-image-2.0-2026-03-03: Mesmas capacidades. A versão acelerada equilibra desempenho e qualidade do modelo. Suporta apenas chamadas síncronas.
-
Modelos de texto para imagem: Geram imagens a partir de descrições em texto.
qwen-image-maxeqwen-image-max-2025-12-30: Mesmas capacidades. Em comparação com oqwen-image-plus, oferecem realismo e naturalidade aprimorados, com melhores resultados em texturas de personagens, detalhes e renderização de texto.qwen-imageeqwen-image-plus: Mesmas capacidades, mas oqwen-image-plusapresenta melhor custo-benefício.qwen-image-plus-2026-01-09: Uma nova versão snapshot do Qwen-Image. Trata-se de uma versão destilada e acelerada doqwen-image-maxque suporta geração rápida de imagens de alta qualidade.
-
Modelo de edição de imagens:
qwen-image-edit: Executa transformações de imagem para imagem, preenchimento (inpainting) e outras operações com base em uma imagem de entrada e instruções de texto. Para mais informações, consulte Qwen - edição de imagens.
P: Como obtenho a lista de permissões de nomes de domínio para armazenamento de imagens?
R: As imagens geradas pelos modelos são armazenadas no OSS. A API retorna uma URL pública temporária. Para configurar uma lista de permissões de firewall para essa URL de download, observe o seguinte: O armazenamento subjacente pode mudar dinamicamente. Este tópico não fornece uma lista fixa de nomes de domínio do OSS para evitar problemas de acesso causados por informações desatualizadas. Se você tiver requisitos de controle de segurança, entre em contato com seu gerente de conta para obter a lista mais recente de nomes de domínio do OSS.
