O Wan2.7-Image oferece suporte a texto para imagem, texto para conjunto de imagens, imagem para conjunto de imagens, edição de imagens e geração com referência a múltiplas imagens.
Visão geral do modelo
|
Modelo |
Descrição |
Especificações da imagem de saída |
|
wan2.7-image-pro |
Wan 2.7 image Pro. Oferece suporte a saída em 4K para geração de texto para imagem (não aplicável a conjuntos de imagens). |
Formato da imagem: PNG. Para resolução e dimensões da imagem, consulte o parâmetro size. |
|
wan2.7-image |
Wan 2.7 image. Geração mais rápida. |
Antes de chamar um modelo, verifique a Lista de modelos e preços para confirmar a disponibilidade regional do modelo.
Pré-requisitos
Obtenha uma chave de API e exporte a chave de API como uma variável de ambiente.
As regiões China (Beijing) e Singapore possuem chaves de API e endpoints de solicitação separados. Eles não podem ser usados de forma intercambiável. Chamadas entre regiões resultam em falhas de autenticação ou erros de service.
HTTP síncrono
Retorna o resultado em uma única solicitação. Recomendado para a maioria dos casos de uso.
Singapore
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
Substitua {WorkspaceId} pelo seu ID do workspace real.
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 solicitação |
Texto para imagemO modelo wan2.7-image-pro suporta resolução 4K apenas para geração de texto para imagem. A edição de imagens e a geração de conjuntos de imagens suportam até resolução 2K.
Edição de imagem
Edição interativa
Geração de conjunto de imagens
|
Headers |
|
|
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. |
|
Corpo da solicitação |
|
|
model Nome do modelo. Valores válidos: |
|
|
input Objeto de entrada. |
|
|
parameters Configurações de parâmetros do modelo. |
Parâmetros da resposta |
Execução bem-sucedida da tarefaOs dados da tarefa (status da tarefa e URLs das imagens) são retidos por apenas 24 horas e depois removidos automaticamente. Salve as imagens geradas prontamente.
Execução anormal da tarefaSe uma tarefa falhar, os campos
|
|
output Informações de saída da tarefa. |
|
|
usage Estatísticas de uso da solicitação. Apenas resultados bem-sucedidos são contabilizados. |
|
|
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. |
HTTP assíncrono
Ideal para tarefas de longa duração. Envie uma tarefa e consulte periodicamente o status e os resultados.
Etapa 1: Crie uma tarefa para obter o ID da tarefa
Singapore
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation
Substitua {WorkspaceId} pelo seu ID do workspace real.
Beijing
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation
Substitua {WorkspaceId} pelo seu ID do workspace real.
Parâmetros da requisição |
Texto para imagemO modelo wan2.7-image-pro suporta resolução 4K apenas para geração de texto para imagem. A edição de imagens e a geração de conjuntos de imagens suportam até resolução 2K.
Edição de imagem
Edição interativa
Geração de conjunto de imagensO modelo wan2.7-image-pro suporta até resolução 2K para geração de conjuntos de imagens.
|
Headers |
|
|
Content-Type 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. |
|
|
X-DashScope-Async Ativa o processamento assíncrono. Requisições HTTP suportam apenas chamadas assíncronas. O valor deve ser Importante
Se este header de requisição estiver ausente, o erro "current user api does not support synchronous calls" será retornado. |
|
Corpo da requisição |
|
|
model Nome do modelo. Valores válidos: |
|
|
input Objeto de entrada. |
|
|
parameters Configurações de parâmetros do modelo. |
Parâmetros da resposta |
Resposta de sucessoSalve 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 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. |
Etapa 2: Consultar o resultado pelo ID da tarefa
Singapore
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Beijing
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
Parâmetros da requisição |
Consultar resultado da tarefaSubstitua |
Headers |
|
|
Authorization Autentica a requisição com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx. |
|
Parâmetros de caminho |
|
|
task_id O ID da tarefa. |
Parâmetros da resposta |
Execução bem-sucedida da tarefaOs dados da tarefa (status e URLs das imagens) são mantidos por apenas 24 horas e depois removidos automaticamente. Salve as imagens geradas imediatamente.
Execução anormal da tarefaSe uma tarefa falhar, os campos
|
|
output Informações de saída da tarefa. |
|
|
usage Estatísticas de uso da requisição. Apenas resultados bem-sucedidos são contabilizados. |
|
|
request_id Identificador exclusivo 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. |
SDK do Python
Os nomes dos parâmetros do SDK são praticamente idênticos aos da API HTTP.
Como as tarefas de geração de imagens podem levar tempo, o SDK encapsula o fluxo de trabalho assíncrono via HTTP. Tanto chamadas síncronas quanto assíncronas são suportadas.
A duração da tarefa depende do tamanho da fila e do status do service.
Certifique-se de que sua versão do DashScope Python SDK seja 1.25.15 ou posterior. Para atualizar, consulte Instalar SDK.
Tanto base_url quanto a chave de API são específicas da região. O exemplo abaixo utiliza a região Singapore:
China (Beijing)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
Ao fazer a chamada, substitua {WorkspaceId} pelo seu workspace ID real.
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
Ao fazer a chamada, substitua {WorkspaceId} pelo seu workspace ID real.
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
Ao fazer a chamada, substitua {WorkspaceId} pelo seu workspace ID real.
China (Beijing)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
Ao fazer a chamada, substitua {WorkspaceId} pelo seu workspace ID real.
Edição de imagens
Chamada síncrona
Exemplo de requisição
import os
import base64
import mimetypes
import urllib.request
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
# The following base_url is for the Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. The base_url varies by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# If you have not configured environment variables, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API key varies by region. To obtain an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# --- Base64 encoding function ---
# The Base64 encoding format is data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if not mime_type or not mime_type.startswith("image/"):
raise ValueError("Unsupported or unrecognized image format")
with open(file_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
return f"data:{mime_type};base64,{encoded_string}"
"""
Image input methods:
The following are three methods for image input. You need to choose only one.
1. Use a public URL: This method is suitable for publicly accessible images.
2. Use a local file: This method is suitable for local development and testing.
3. Use Base64 encoding: This method is suitable for private images or scenarios that require encrypted transmission.
"""
# [Method 1] Use a public image URL
image_1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"
image_2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"
# [Method 2] Use a local file (supports absolute and relative paths)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"
# [Method 3] Use a Base64-encoded image
# image_1 = encode_file("/path/to/your/car.png")
# image_2 = encode_file("/path/to/your/paint.png")
message = Message(
role="user",
content=[
{"text": "Spray the graffiti from image 2 onto the car in image 1"},
{"image": image_1},
{"image": image_2},
],
)
print("----sync call, please wait a moment----")
rsp = ImageGeneration.call(
model="wan2.7-image-pro",
api_key=api_key,
messages=[message],
watermark=False,
n=1,
size="2K", # wan2.7-image-pro supports 4K resolution only for text-to-image generation. Image editing and multi-image generation support up to 2K resolution.
)
# Extract the result image URL and save the image to a local file.
if rsp.status_code == 200:
for i, choice in enumerate(rsp.output.choices):
for j, content in enumerate(choice["message"]["content"]):
if content.get("type") == "image":
image_url = content["image"]
file_name = f"output_{i}_{j}.png"
# The result URL is valid for 24 hours. Please download it promptly.
urllib.request.urlretrieve(image_url, file_name)
print(f"Image saved to {file_name}")
else:
print(f"Failed: status_code={rsp.status_code}, message={rsp.message}")
Exemplo de resposta
A URL é válida por 24 horas. Baixe a imagem imediatamente.
{
"status_code": 200,
"request_id": "81d868c6-6ce1-92d8-a90d-d2ee71xxxxxx",
"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": 18790,
"output_tokens": 2,
"characters": 0,
"image_count": 1,
"size": "2985*1405",
"total_tokens": 18792
}
}
Chamada assíncrona
Exemplo de requisição
import os
import base64
import mimetypes
import urllib.request
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
from http import HTTPStatus
# The following base_url is for the Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. The base_url varies by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# If you have not configured environment variables, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API key varies by region. To obtain an API key, visit https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# --- Base64 encoding function ---
# The Base64 encoding format is data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if not mime_type or not mime_type.startswith("image/"):
raise ValueError("Unsupported or unrecognized image format.")
with open(file_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
return f"data:{mime_type};base64,{encoded_string}"
"""
Image input methods:
Three image input methods are provided below. Choose one.
1. Use a public URL - suitable for publicly accessible images.
2. Use a local file - suitable for local development and testing.
3. Use Base64 encoding - suitable for private images or scenarios that require encrypted transmission.
"""
# [Method 1] Use a public image URL
image_1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"
image_2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"
# [Method 2] Use a local file (supports absolute and relative paths)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"
# [Method 3] Use a Base64-encoded image
# image_1 = encode_file("/path/to/your/car.png")
# image_2 = encode_file("/path/to/your/paint.png")
# Create an asynchronous task.
def create_async_task():
print("Creating async task...")
message = Message(
role="user",
content=[
{"text": "Spray the graffiti from image 2 onto the car in image 1."},
{"image": image_1},
{"image": image_2},
],
)
response = ImageGeneration.async_call(
model="wan2.7-image-pro",
api_key=api_key,
messages=[message],
watermark=False,
n=1,
size="2K", # wan2.7-image-pro supports 4K resolution only for text-to-image generation scenarios. Image editing and collage generation support a maximum resolution of 2K.
)
if response.status_code == 200:
print("Task created successfully:", response)
return response
else:
raise Exception(f"Failed to create task: {response.code} - {response.message}")
# Wait for the task to complete.
def wait_for_completion(task_response):
print("Waiting for task completion...")
status = ImageGeneration.wait(task=task_response, api_key=api_key)
if status.output.task_status == "SUCCEEDED":
print("Task succeeded!")
# Extract the result image URL and save the image to a local file.
for i, choice in enumerate(status.output.choices):
for j, content in enumerate(choice["message"]["content"]):
if content.get("type") == "image":
image_url = content["image"]
file_name = f"output_{i}_{j}.png"
# The result URL is valid for 24 hours. Download the image in a timely manner.
urllib.request.urlretrieve(image_url, file_name)
print(f"Image saved to {file_name}")
else:
raise Exception(f"Task failed with status: {status.output.task_status}")
# Obtain information about the asynchronous task.
def fetch_task_status(task):
print("Fetching task status...")
status = ImageGeneration.fetch(task=task, api_key=api_key)
if status.status_code == HTTPStatus.OK:
print("Task status:", status.output.task_status)
print("Response details:", status)
else:
print(f"Failed to fetch status: {status.code} - {status.message}")
# Cancel the asynchronous task.
def cancel_task(task):
print("Canceling task...")
response = ImageGeneration.cancel(task=task, api_key=api_key)
if response.status_code == HTTPStatus.OK:
print("Task canceled successfully:", response.output.task_status)
else:
print(f"Failed to cancel task: {response.code} - {response.message}")
# Main execution flow.
if __name__ == "__main__":
task = create_async_task()
wait_for_completion(task)
Exemplo de resposta
-
Exemplo de resposta ao criar uma tarefa
{ "status_code": 200, "request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx", "code": "", "message": "", "output": { "text": null, "finish_reason": null, "choices": null, "audio": null, "task_id": "127ec645-118f-4884-955d-0eba8dxxxxxx", "task_status": "PENDING" }, "usage": { "input_tokens": 0, "output_tokens": 0, "characters": 0 } } -
Exemplo de resposta ao consultar o resultado de uma tarefa
A URL é válida por 24 horas. Baixe a imagem imediatamente.
{ "status_code": 200, "request_id": "3b99aae5-d26f-9059-8dd0-ee9ca4804xxx", "code": null, "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, "task_id": "127ec645-118f-4884-955d-0eba8dxxxxxx", "task_status": "SUCCEEDED", "submit_time": "2026-03-31 22:58:47.646", "scheduled_time": "2026-03-31 22:58:47.683", "end_time": "2026-03-31 22:58:59.642", "finished": true }, "usage": { "input_tokens": 18711, "output_tokens": 2, "characters": 0, "size": "2985*1405", "total_tokens": 18713, "image_count": 1 } }
Instruções
Leia o conteúdo em inglês para entender O QUE precisa ser comunicado
Escreva o português brasileiro DO ZERO — esqueça a estrutura das frases em inglês
Preserve toda a formatação markdown, blocos de código, links e imagens exatamente como estão
Tags xref (
<a data-tag="xref" ...>texto</a>) — preserve a tag INTEIRA com todos os atributos na ordem e caixa originais, traduza APENAS o texto visível entre > eAplique todas as regras específicas do idioma rigorosamente
Aplique as regras de stopwords com tolerância zero
Use o modo imperativo em etapas numeradas e listas de procedimentos
Garanta consistência terminológica — mesmo termo = mesma tradução em todo o documento
Varie os inícios de frase em listas/tabelas — nenhum início repetido mais de 3 vezes
-
Retorne APENAS o documento markdown em português brasileiro, sem explicações
Geração de conjunto de imagens
Chamada síncrona
Exemplo de solicitação
import os import base64 import mimetypes import urllib.request import dashscope from dashscope.aigc.image_generation import ImageGeneration from dashscope.api_entities.dashscope_response import Message # The following base_url is for the Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. The base_url varies by region. dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1" # If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx" # The API key varies by region. To obtain an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-key api_key = os.getenv("DASHSCOPE_API_KEY") # --- Base64 encoding function --- # The Base64 encoding format is data:{MIME_type};base64,{base64_data} def encode_file(file_path): mime_type, _ = mimetypes.guess_type(file_path) if not mime_type or not mime_type.startswith("image/"): raise ValueError("Unsupported or unrecognized image format") with open(file_path, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode("utf-8") return f"data:{mime_type};base64,{encoded_string}" """ Description of image input methods (for image-to-image sequence generation): Choose one of the following three image input methods: 1. Use a public URL - Suitable for publicly accessible images. 2. Use a local file - Suitable for local development and testing. 3. Use Base64 encoding - Suitable for private images or scenarios that require encrypted transmission. """ # [Method 1] Use a public image URL # image_1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp" # [Method 2] Use a local file (supports both absolute and relative paths) # image_1 = "file:///path/to/your/image.png" # [Method 3] Use a Base64-encoded image # image_1 = encode_file("/path/to/your/image.png") message = Message( role="user", content=[ { "text": "A cinematic image sequence featuring the same stray orange cat, whose features must be consistent across all images. First image: In spring, the orange cat weaves through blooming cherry blossom trees. Second image: In summer, the orange cat cools off in the shade of a tree on an old street. Third image: In autumn, the orange cat walks on a carpet of golden fallen leaves. Fourth image: In winter, the orange cat leaves footprints as it walks on the snow." } # For image-to-image sequence generation: Uncomment the following lines and comment out the plain text above. # {"text": "Generate a four-seasons image sequence based on the style of the reference image"}, # {"image": image_1} ], ) print("----sync call, please wait a moment----") rsp = ImageGeneration.call( model="wan2.7-image-pro", api_key=api_key, messages=[message], enable_sequential=True, n=4, size="2K", # wan2.7-image-pro supports 4K resolution only in text-to-image scenarios. Image editing and image sequence generation support a maximum resolution of 2K. ) # Extract the resulting image URLs and save the images locally. if rsp.status_code == 200: for i, choice in enumerate(rsp.output.choices): for j, content in enumerate(choice["message"]["content"]): if content.get("type") == "image": image_url = content["image"] file_name = f"output_{i}_{j}.png" # The result URL is valid for 24 hours. Download the image promptly. urllib.request.urlretrieve(image_url, file_name) print(f"Image saved to {file_name}") else: print(f"Failed: status_code={rsp.status_code}, message={rsp.message}")Exemplo de resposta
A URL tem validade de 24 horas. Baixe a imagem prontamente.
{ "status_code": 200, "request_id": "56e318fd-ed60-99e8-8ca1-cdef25ca4xxx", "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" }, { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" }, { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" }, { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" } ] } } ], "audio": null, "finished": true }, "usage": { "input_tokens": 720, "output_tokens": 11, "characters": 0, "image_count": 4, "size": "2048*2048", "total_tokens": 731 } }Chamada assíncrona
Exemplo de solicitação
import os import base64 import mimetypes import urllib.request import dashscope from dashscope.aigc.image_generation import ImageGeneration from dashscope.api_entities.dashscope_response import Message # The following base_url is for the Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. The base_url varies by region. dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1" # If you have not configured the DASHSCOPE_API_KEY environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx" # The API key varies by region. To obtain an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-key api_key = os.getenv("DASHSCOPE_API_KEY") # --- Base64 encoding function --- # The Base64 data URI scheme is data:{MIME_type};base64,{base64_data} def encode_file(file_path): mime_type, _ = mimetypes.guess_type(file_path) if not mime_type or not mime_type.startswith("image/"): raise ValueError("Unsupported or unrecognized image format") with open(file_path, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode("utf-8") return f"data:{mime_type};base64,{encoded_string}" """ Description of image input methods (for image-to-image sequence generation): The following three image input methods are provided. Choose one of them. 1. Use a public URL: Suitable for images that are publicly accessible. 2. Use a local file: Suitable for local development and testing. 3. Use Base64 encoding: Suitable for private images or scenarios that require encrypted transmission. """ # [Method 1] Use a public image URL # image_1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp" # [Method 2] Use a local file (absolute and relative paths are supported) # image_1 = "file:///path/to/your/image.png" # [Method 3] Use a Base64-encoded image # image_1 = encode_file("/path/to/your/image.png") def main(): message = Message( role="user", content=[ { "text": "A cinematic sequence of images documenting the same stray orange cat, whose features must remain consistent across all images. Image 1: In spring, the cat weaves through blooming cherry blossom trees. Image 2: In summer, the cat cools off in the shade of trees on an old street. Image 3: In autumn, the cat steps on a carpet of golden fallen leaves. Image 4: In winter, the cat walks on the snow, leaving footprints." } # Image-to-image sequence generation scenario: Uncomment the following lines and comment out the plain text above. # {"text": "Generate a sequence of four seasonal images based on the style of the reference image."}, # {"image": image_1} ], ) # Submit an asynchronous task print("Submitting an asynchronous task...") response = ImageGeneration.async_call( model="wan2.7-image-pro", api_key=api_key, messages=[message], enable_sequential=True, n=4, size="2K", # wan2.7-image-pro supports 4K resolution only in text-to-image scenarios. Image editing and image sequence generation support a maximum resolution of 2K. ) if response.status_code == 200: print(f"Task submitted successfully. Task ID: {response.output.task_id}") # Wait for the task to complete status = ImageGeneration.wait(task=response, api_key=api_key) if status.output.task_status == "SUCCEEDED": print("Task completed!") # Extract the result image URLs and save them to a local device. for i, choice in enumerate(status.output.choices): for j, content in enumerate(choice["message"]["content"]): if content.get("type") == "image": image_url = content["image"] file_name = f"output_{i}_{j}.png" # The result URLs are valid for 24 hours. Download the images in a timely manner. urllib.request.urlretrieve(image_url, file_name) print(f"Image saved to {file_name}") else: print(f"Task failed. Status: {status.output.task_status}") else: print(f"Failed to create the task: {response.code} - {response.message}") if __name__ == "__main__": try: main() except Exception as e: print(f"Error: {e}")Exemplo de resposta
-
Exemplo de resposta para criação de tarefa
{ "status_code": 200, "request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx", "code": "", "message": "", "output": { "text": null, "finish_reason": null, "choices": null, "audio": null, "task_id": "77093787-a217-4c29-9cd4-ca7b5ac86xxx", "task_status": "PENDING" }, "usage": { "input_tokens": 0, "output_tokens": 0, "characters": 0 } } -
Exemplo de resposta para consulta de resultado de tarefa
A URL tem validade de 24 horas. Baixe a imagem prontamente.
{ "status_code": 200, "request_id": "56e318fd-ed60-99e8-8ca1-cdef25ca4xxx", "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" }, { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" }, { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" }, { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" } ] } } ], "audio": null, "task_id": "77093787-a217-4c29-9cd4-ca7b5ac86xxx", "task_status": "SUCCEEDED", "submit_time": "2026-03-31 23:04:46.166", "scheduled_time": "2026-03-31 23:04:46.208", "end_time": "2026-03-31 23:05:11.664", "finished": true }, "usage": { "input_tokens": 720, "output_tokens": 11, "characters": 0, "size": "2048*2048", "total_tokens": 731, "image_count": 4 } }
-
Java SDK
Os nomes dos parâmetros do SDK são amplamente consistentes com os da HTTP API.
Como as tarefas de geração de imagens podem levar tempo, o SDK encapsula o fluxo de trabalho assíncrono via HTTP. Tanto chamadas síncronas quanto assíncronas são suportadas.
Certifique-se de que sua versão do DashScope Java SDK seja 2.22.13 ou posterior.
China (Beijing)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do workspace real.
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do workspace real.
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do workspace real.
China (Beijing)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do workspace real.
Edição de imagem
Chamada síncrona
Exemplo de solicitação
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.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* wan2.7-image-pro Image Editing - Synchronous Call Example
*/
public class Main {
static {
// The following URL is for the Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. The base_url varies by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If you have not configured an environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
// The API key varies by region. To obtain an API key, visit https://www.alibabacloud.com/help/en/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
// --- Base64 encoding function ---
// Base64 encoding format: data:{MIME_type};base64,{base64_data}
public static String encodeFile(String filePath) throws IOException {
byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
String base64String = Base64.getEncoder().encodeToString(fileContent);
String mimeType = Files.probeContentType(Paths.get(filePath));
return "data:" + mimeType + ";base64," + base64String;
}
public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
/*
* Description of image input methods:
* Three image input methods are provided below. Select one.
* 1. Use a public URL: Suitable for publicly accessible images.
* 2. Use a local file: Suitable for local development and testing.
* 3. Use Base64 encoding: Suitable for private images or scenarios that require encrypted transmission.
*/
// Method 1: Use a public image URL.
String image1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp";
String image2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp";
// Method 2: Use a local file. Both absolute and relative paths are supported.
// Format: file:// + file path
// String image1 = "file:///path/to/your/car.png";
// String image2 = "file:///path/to/your/paint.png";
// Method 3: Use a Base64-encoded image.
// String image1 = encodeFile("/path/to/your/car.png");
// String image2 = encodeFile("/path/to/your/paint.png");
// Build a multi-image input message.
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Arrays.asList(
// Multi-image input is supported. You can provide multiple reference images.
Collections.singletonMap("text", "Spray the graffiti from image 2 onto the car in image 1"),
Collections.singletonMap("image", image1),
Collections.singletonMap("image", image2)
)).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.7-image-pro")
.messages(Collections.singletonList(message))
.n(1)
.size("2K") // For wan2.7-image-pro, only the text-to-image generation scenario supports 4K resolution. Image editing and collage generation support a maximum resolution of 2K.
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = null;
try {
System.out.println("---sync call for image editing, please wait a moment----");
result = imageGeneration.call(param);
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
// Extract the result image URL and save it to a local file.
for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
.getMessage().getContent();
for (int j = 0; j < contents.size(); j++) {
if ("image".equals(contents.get(j).get("type"))) {
String imageUrl = (String) contents.get(j).get("image");
String fileName = "output_" + i + "_" + j + ".png";
// The result URL is valid for 24 hours. Download the image in a timely manner.
try (InputStream in = new URL(imageUrl).openStream()) {
Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
}
System.out.println("Image saved to " + fileName);
}
}
}
}
public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
basicCall();
}
}
Exemplo de resposta
A URL tem validade de 24 horas. Salve-a prontamente.
{
"requestId": "1bf6173a-e8de-9f75-94d3-5e618f875xxx",
"usage": {
"input_tokens": 18790,
"output_tokens": 2,
"total_tokens": 18792,
"image_count": 1,
"size": "2985*1405"
},
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
}
]
}
}
],
"finished": true
},
"status_code": 200,
"code": "",
"message": ""
}
Chamada assíncrona
Exemplo de solicitação
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.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* wan2.7-image-pro Image Editing - Asynchronous Invocation Example
*/
public class Main {
static {
// The following URL is for the Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. The base_url varies by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If you have not configured an environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
// The API key varies by region. To obtain an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
// --- Base64 encoding function ---
// The Base64 encoding format is data:{MIME_type};base64,{base64_data}
public static String encodeFile(String filePath) throws IOException {
byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
String base64String = Base64.getEncoder().encodeToString(fileContent);
String mimeType = Files.probeContentType(Paths.get(filePath));
return "data:" + mimeType + ";base64," + base64String;
}
public static void asyncCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
/*
* Description of image input methods:
* The following three image input methods are provided. You can choose one of them.
* 1. Use a public URL - Suitable for publicly accessible images.
* 2. Use a local file - Suitable for local development and testing.
* 3. Use Base64 encoding - Suitable for scenarios that involve private images or require encrypted transmission.
*/
// [Method 1] Use a public image URL
String image1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp";
String image2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp";
// [Method 2] Use a local file (supports absolute and relative paths)
// Required format: file:// + file path
// String image1 = "file:///path/to/your/car.png";
// String image2 = "file:///path/to/your/paint.png";
// [Method 3] Use a Base64-encoded image
// String image1 = encodeFile("/path/to/your/car.png");
// String image2 = encodeFile("/path/to/your/paint.png");
// Build a multi-image input message
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Arrays.asList(
// Supports multi-image input. You can provide multiple reference images.
Collections.singletonMap("text", "Spray-paint the graffiti from image 2 onto the car in image 1"),
Collections.singletonMap("image", image1),
Collections.singletonMap("image", image2)
)).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.7-image-pro")
.n(1)
.size("2K") // The wan2.7-image-pro model supports 4K resolution only for text-to-image generation. For image editing and composite image generation, the maximum supported resolution is 2K.
.messages(Arrays.asList(message))
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = null;
try {
System.out.println("---async call for image editing, creating task----");
result = imageGeneration.asyncCall(param);
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
System.out.println("Task creation result:");
System.out.println(JsonUtils.toJson(result));
String taskId = result.getOutput().getTaskId();
// Wait for the task to complete
waitTask(taskId);
}
public static void waitTask(String taskId) throws ApiException, NoApiKeyException, IOException {
ImageGeneration imageGeneration = new ImageGeneration();
System.out.println("\n---waiting for task completion----");
ImageGenerationResult result = imageGeneration.wait(taskId, apiKey);
// Fetch the resulting image URL and save it to a local file
for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
.getMessage().getContent();
for (int j = 0; j < contents.size(); j++) {
if ("image".equals(contents.get(j).get("type"))) {
String imageUrl = (String) contents.get(j).get("image");
String fileName = "output_" + i + "_" + j + ".png";
// The result URL is valid for 24 hours. Download the image in a timely manner.
try (InputStream in = new URL(imageUrl).openStream()) {
Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
}
System.out.println("Image saved to " + fileName);
}
}
}
}
public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
asyncCall();
}
}
Exemplo de resposta
-
Exemplo de resposta para criação de tarefa
{ "requestId": "ccf4b2f4-bf30-9e13-9461-3a28c6a7bxxx", "output": { "task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx", "task_status": "PENDING" }, "status_code": 200, "code": "", "message": "" } -
Exemplo de resposta para consulta de resultado de tarefa
A URL é válida por 24 horas. Salve-a prontamente.
{ "requestId": "60a08540-f1c1-9e76-8cd3-d5949db8cxxx", "usage": { "input_tokens": 18711, "output_tokens": 2, "total_tokens": 18713, "image_count": 1, "size": "2985*1405" }, "output": { "choices": [ { "finish_reason": "stop", "message": { "role": "assistant", "content": [ { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" } ] } } ], "task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx", "task_status": "SUCCEEDED", "finished": true, "submit_time": "2026-03-31 19:57:58.840", "scheduled_time": "2026-03-31 19:57:58.877", "end_time": "2026-03-31 19:58:11.563" }, "status_code": 200, "code": "", "message": "" }
Geração de conjunto de imagens
Chamada síncrona
Exemplo de solicitação
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.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* An example of using wan2.7-image-pro for image series generation through synchronous calls in the Singapore region.
*/
public class Main {
static {
// The following URL is for the Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. The base_url varies by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
// API keys vary by region. To obtain an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
// --- Base64 encoding function ---
// The format for Base64 encoding is data:{MIME_type};base64,{base64_data}
public static String encodeFile(String filePath) throws IOException {
byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
String base64String = Base64.getEncoder().encodeToString(fileContent);
String mimeType = Files.probeContentType(Paths.get(filePath));
return "data:" + mimeType + ";base64," + base64String;
}
public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
/*
* Image input methods (for image-to-image series generation):
* Three image input methods are provided below. Choose one.
* 1. Public URL: Suitable for images that are already publicly accessible.
* 2. Local file: Suitable for local development and testing.
* 3. Base64 encoding: Suitable for private images or scenarios that require encrypted transmission.
*/
// Method 1: Use a public image URL
// String image1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp";
// Method 2: Use a local file (supports both absolute and relative paths)
// Format: file:// + file path
// String image1 = "file:///path/to/your/image.png";
// Method 3: Use a Base64-encoded image
// String image1 = encodeFile("/path/to/your/image.png");
// Build the text input message. This supports both text-to-image and image-to-image series generation. This example demonstrates text-to-image series generation.
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Collections.singletonList(
Collections.singletonMap("text", "A cinematic image series documenting the same stray orange cat, whose features must remain consistent. First image: In spring, the cat weaves through blooming cherry blossom trees. Second image: In summer, the cat cools off in the shade on an old street. Third image: In autumn, the cat walks on a carpet of golden fallen leaves. Fourth image: In winter, the cat leaves footprints in the snow.")
)).build();
// For image-to-image series generation, uncomment the following code and comment out the plain text message builder above.
// ImageGenerationMessage message = ImageGenerationMessage.builder()
// .role("user")
// .content(Arrays.asList(
// Collections.singletonMap("text", "Generate a four-season image series based on the style of the reference image."),
// Collections.singletonMap("image", image1)
// )).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.7-image-pro")
.messages(Collections.singletonList(message))
.enableSequential(true)
.n(4)
.size("2K") // The wan2.7-image-pro model supports 4K resolution only for text-to-image generation. Image editing and image series generation support a maximum resolution of 2K.
.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());
}
// Extract the resulting image URLs and save them to a local directory.
for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
.getMessage().getContent();
for (int j = 0; j < contents.size(); j++) {
if ("image".equals(contents.get(j).get("type"))) {
String imageUrl = (String) contents.get(j).get("image");
String fileName = "output_" + i + "_" + j + ".png";
// The resulting URL is valid for 24 hours. Be sure to download it promptly.
try (InputStream in = new URL(imageUrl).openStream()) {
Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
}
System.out.println("Image saved to " + fileName);
}
}
}
}
public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
basicCall();
}
}
Exemplo de resposta
A URL é válida por 24 horas. Salve-a prontamente.
{
"requestId": "4678c314-b37a-91c9-a2ae-2d3cd54bbxxx",
"usage": {
"input_tokens": 720,
"output_tokens": 11,
"total_tokens": 731,
"image_count": 4,
"size": "2048*2048"
},
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
},
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
},
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
},
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
}
]
}
}
],
"finished": true
},
"status_code": 200,
"code": "",
"message": ""
}
Chamada assíncrona
Exemplo de solicitação
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.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* wan2.7-image-pro Image Set Generation - Asynchronous Invocation Example (Singapore Region)
*/
public class Main {
static {
// The following URL is for the Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. The base_url varies by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If you have not configured environment variables, replace the following line with your Model Studio API key: apiKey="sk-xxx"
// The API key varies by region. To obtain an API key, visit https://www.alibabacloud.com/help/en/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
// --- Base64 encoding function ---
// The Base64 encoding format is data:{MIME_type};base64,{base64_data}
public static String encodeFile(String filePath) throws IOException {
byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
String base64String = Base64.getEncoder().encodeToString(fileContent);
String mimeType = Files.probeContentType(Paths.get(filePath));
return "data:" + mimeType + ";base64," + base64String;
}
public static ImageGenerationResult waitTask(String taskId)
throws ApiException, NoApiKeyException {
ImageGeneration imageGeneration = new ImageGeneration();
return imageGeneration.wait(taskId, apiKey);
}
public static void asyncCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
/*
* Description of image input methods (for image-to-image set generation scenarios):
* The following three image input methods are provided. You can choose one of them.
* 1. Use a public URL - suitable for publicly accessible images.
* 2. Use a local file - suitable for local development and testing.
* 3. Use Base64 encoding - suitable for private images or scenarios that require encrypted transmission.
*/
// [Method 1] Use a public image URL
// String image1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp";
// [Method 2] Use a local file (supports absolute and relative paths)
// Format: file:// + file path
// String image1 = "file:///path/to/your/image.png";
// [Method 3] Use a Base64-encoded image
// String image1 = encodeFile("/path/to/your/image.png");
// Build the text input message (supports text-to-image set and image-to-image set generation. This example uses text-to-image set generation.)
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Collections.singletonList(
Collections.singletonMap("text", "A cinematic image set documenting the same stray orange cat. Its features must be consistent across all images. Image 1: In spring, the orange cat weaves through blooming cherry blossom trees. Image 2: In summer, the orange cat cools off in the shade of a tree on an old street. Image 3: In autumn, the orange cat steps on a carpet of golden fallen leaves. Image 4: In winter, the orange cat leaves footprints as it walks on the snow.")
)).build();
// For image-to-image set generation scenarios: uncomment the following code and comment out the plain text construction above.
// ImageGenerationMessage message = ImageGenerationMessage.builder()
// .role("user")
// .content(Arrays.asList(
// Collections.singletonMap("text", "Generate an image set of the four seasons based on the style of the reference image."),
// Collections.singletonMap("image", image1)
// )).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.7-image-pro")
.messages(Collections.singletonList(message))
.enableSequential(true)
.n(4)
.size("2K") // The wan2.7-image-pro model supports 4K resolution only for text-to-image generation. Image editing and image set generation support a maximum resolution of 2K.
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult taskResult = null;
try {
System.out.println("----async call, creating task----");
taskResult = imageGeneration.asyncCall(param);
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
System.out.println("Task created: " + JsonUtils.toJson(taskResult));
// Wait for the task to complete.
String taskId = taskResult.getOutput().getTaskId();
ImageGenerationResult result = waitTask(taskId);
// Fetch the resulting image URLs and save them to a local directory.
for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
.getMessage().getContent();
for (int j = 0; j < contents.size(); j++) {
if ("image".equals(contents.get(j).get("type"))) {
String imageUrl = (String) contents.get(j).get("image");
String fileName = "output_" + i + "_" + j + ".png";
// The result URL is valid for 24 hours. Download the image in a timely manner.
try (InputStream in = new URL(imageUrl).openStream()) {
Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
}
System.out.println("Image saved to " + fileName);
}
}
}
}
public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
asyncCall();
}
}
Exemplo de resposta
-
Exemplo de resposta para criação de tarefa
{ "requestId": "7d026dc1-e8c9-9caa-84ac-e82e2da97xxx", "output": { "task_id": "2de18c56-c151-4b80-8105-1d164733exxx", "task_status": "PENDING" }, "status_code": 200, "code": "", "message": "" } -
Exemplo de resposta para consulta de resultado de tarefa
A URL é válida por 24 horas. Salve-a prontamente.
{ "requestId": "daea7295-4ce0-928a-9a11-4d2bea058xxx", "usage": { "input_tokens": 720, "output_tokens": 11, "total_tokens": 731, "image_count": 4, "size": "2048*2048" }, "output": { "choices": [ { "finish_reason": "stop", "message": { "role": "assistant", "content": [ { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" }, { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" }, { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" }, { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" } ] } } ], "task_id": "2de18c56-c151-4b80-8105-1d164733exxx", "task_status": "SUCCEEDED", "finished": true, "submit_time": "2026-03-31 19:49:53.124", "scheduled_time": "2026-03-31 19:49:53.175", "end_time": "2026-03-31 19:50:53.160" }, "status_code": 200, "code": "", "message": "" }
Faturamento e limitação de taxa
Para consultar a cota gratuita e o preço unitário do modelo, consulte Preços do modelo.
Para informações sobre limitação de taxa do modelo, consulte Wanxiang.
Detalhes do faturamento: A cobrança é baseada no número de imagens geradas com sucesso. Chamadas com falha e erros de processamento não geram custos 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 obter a resolução.