O modelo Wanxiang General Image Editing wan2.5 edita e funde imagens a partir apenas de instruções de texto, mantendo a consistência do assunto em todas as edições.
Início rápido: Guia do usuário
O Alibaba Cloud Model Studio lançou domínios específicos por workspace para as regiões China (Beijing) e Singapore. Os novos domínios dedicados oferecem desempenho superior e maior estabilidade para solicitações de inferência. Recomendamos migrar para os novos domínios:
China (Beijing): de
https://dashscope.aliyuncs.comparahttps://{WorkspaceId}.cn-beijing.maas.aliyuncs.comSingapore: de
https://dashscope-intl.aliyuncs.comparahttps://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
{WorkspaceId} é o ID do seu workspace, que pode ser encontrado na página Workspace Details no console do Alibaba Cloud Model Studio. O domínio existente permanece totalmente funcional.
Visão geral do modelo
|
Capacidades do modelo |
Exemplo de entrada |
Imagem de saída |
|
Edição de imagem única |
|
Substitua o vestido floral por um vestido de renda estilo vintage com bordados delicados na gola e nos punhos. |
|
Fusão de múltiplas imagens |
|
Coloque o despertador da imagem 1 ao lado do vaso sobre a mesa de jantar na imagem 2. |
|
Nome do modelo |
Descrição do modelo |
Especificações da imagem de saída |
|
wan2.5-i2i-preview |
Wanxiang 2.5 preview Suporta edição de imagem única e fusão de múltiplas imagens |
Formato da imagem: PNG. Resolução da imagem:
|
Antes de chamar a API, revise os modelos suportados e preços 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 fazer chamadas usando o SDK, instale o DashScope SDK.
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.
Chamada de API HTTP
A edição de imagens leva de 1 a 2 minutos, portanto a API usa invocação assíncrona: Criar tarefa → Consultar resultado.
O tempo real de execução varia conforme o tamanho da fila e a carga do service.
Etapa 1: Criar uma tarefa e obter o ID da tarefa
Região Singapore: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis
Região Beijing: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis
Substitua {WorkspaceId} pelo seu ID do workspace real.
Após criar a tarefa, use o
task_idretornado para consultar o resultado. Otask_idé válido por 24 horas. Não crie tarefas duplicadas. Em vez disso, use polling para recuperar o resultado.Para orientações destinadas a iniciantes, consulte Chamar APIs com Postman ou cURL.
Parâmetros da solicitação |
Edição de imagem única
Fusão de múltiplas imagens
|
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. Deve ser Importante
Se 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. Modelos suportados e preços. Valor de exemplo: wan2.5-i2i-preview. |
|
|
input Campos de entrada, como o prompt e as imagens. |
|
|
parameters Controla resolução, reescrita de prompt e marca d'água. |
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 chamar, substitua {WorkspaceId} pelo seu ID do workspace real.
Singapore
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Ao chamar, substitua {WorkspaceId} pelo seu ID do workspace real.
Singapore
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Ao chamar, substitua {WorkspaceId} pelo seu ID do workspace real.
China (Beijing)
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
Ao chamar, substitua {WorkspaceId} pelo seu ID do workspace real.
Recomendação de polling: A geração de imagens demanda tempo. Use um mecanismo de polling com um 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 resultado da tarefaSubstitua As chaves de API são diferentes para cada região. Para mais informações, consulte Obter uma chave de API. Se você usar um modelo na região China (Beijing), substitua
|
Cabeçalhos da solicitação |
|
|
Authorization Autentica a solicitação com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx. |
|
Parâmetro de caminho da URL |
|
|
task_id O ID da tarefa. |
Parâmetros da resposta |
Tarefa bem-sucedidaAs URLs das imagens são válidas apenas por 24 horas e depois são removidas automaticamente. Salve as imagens geradas prontamente. Tarefa falhouQuando uma tarefa falha,
Falha parcialO modelo pode gerar múltiplas imagens por tarefa. Se pelo menos uma for bem-sucedida, o status da tarefa é
Consulta de tarefa expiradaO
|
|
output Informações de saída da tarefa. |
|
|
usage Estatísticas de uso. Conta apenas resultados bem-sucedidos. |
|
|
request_id Identificador único da solicitação para rastreamento e solução de problemas. |
Chamada via DashScope SDK
Os parâmetros do SDK correspondem à Chamada de API HTTP, encapsulados para adequar-se a cada linguagem.
A edição de imagens leva de 30 a 60 segundos. O SDK encapsula o fluxo HTTP assíncrono, suportando chamadas síncronas e assíncronas.
O tempo real de execução varia conforme o tamanho da fila e a carga do service.
Chamada via Python SDK
Certifique-se de que sua versão do DashScope Python SDK seja pelo menos 1.25.2.
Versões mais antigas podem gerar erros como “url error, please check url!”. Atualize usando Instalar ou atualizar SDK.
Chamada síncrona
Exemplo de solicitação
Este exemplo suporta três métodos de entrada de imagem: URL pública, codificação Base64 e caminho de arquivo local.
import base64
import mimetypes
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import dashscope
import requests
from dashscope import ImageSynthesis
import os
# The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# If you have not configured an environment variable, replace the next line with: api_key="sk-xxx"
# API keys differ between Singapore and Beijing. Get an API key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# --- Input image: Base64 encoding ---
# Base64 format: 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:
Choose one of the following:
1. Public URL — best for publicly accessible images
2. Local file — best for local development and testing
3. Base64 encoding — best for private images or secure transmission
"""
# [Method 1] Public image URL
image_url_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp"
image_url_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
# [Method 2] Local file (supports absolute and relative paths)
# Format: file:// + file path
# Example (absolute path):
# image_url_1 = "file://" + "/path/to/your/image_1.png" # Linux/macOS
# image_url_2 = "file://" + "C:/path/to/your/image_2.png" # Windows
# Example (relative path):
# image_url_1 = "file://" + "./image_1.png" # Adjust to your path
# image_url_2 = "file://" + "./image_2.png" # Adjust to your path
# [Method 3] Base64-encoded image
# image_url_1 = encode_file("./image_1.png") # Adjust to your path
# image_url_2 = encode_file("./image_2.png") # Adjust to your path
print('----sync call, please wait a moment----')
rsp = ImageSynthesis.call(api_key=api_key,
model="wan2.5-i2i-preview",
prompt="Place the alarm clock from image 1 beside the vase on the dining table in image 2.",
images=[image_url_1, image_url_2],
negative_prompt="",
n=1,
# size="1280*1280",
prompt_extend=True,
watermark=False,
seed=12345)
print('response: %s' % rsp)
if rsp.status_code == HTTPStatus.OK:
# Save images to 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('sync_call Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
Exemplo de resposta
As URLs das imagens expiram após 24 horas. Baixe as imagens prontamente.
{
"status_code": 200,
"request_id": "8ad45834-4321-44ed-adf5-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "3aff9ebd-35fc-4339-98a3-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
"orig_prompt": "Place the alarm clock from image 1 beside the vase on the dining table in image 2.",
"actual_prompt": "Place the blue alarm clock from image 1 to the right of the vase on the dining table in image 2, near the edge of the tablecloth. Keep the clock facing the camera and parallel to the tabletop, with natural shadow projection."
}
],
"submit_time": "2025-10-23 16:18:16.009",
"scheduled_time": "2025-10-23 16:18:16.040",
"end_time": "2025-10-23 16:19:09.591",
"task_metrics": {
"TOTAL": 1,
"FAILED": 0,
"SUCCEEDED": 1
}
},
"usage": {
"image_count": 1
}
}
Chamada assíncrona
Este exemplo usa URLs públicas para entrada de imagem.
Exemplo de solicitação
import os
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import dashscope
import requests
from dashscope import ImageSynthesis
# The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# If you have not configured an environment variable, replace the next line with: api_key="sk-xxx"
# API keys differ between Singapore and Beijing. Get an API key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# Public image URLs
image_url_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp"
image_url_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
def async_call():
print('----create task----')
task_info = create_async_task()
print('----wait task----')
wait_async_task(task_info)
# Create an asynchronous task
def create_async_task():
rsp = ImageSynthesis.async_call(api_key=api_key,
model="wan2.5-i2i-preview",
prompt="Place the alarm clock from image 1 beside the vase on the dining table in image 2.",
images=[image_url_1, image_url_2],
negative_prompt="",
n=1,
# size="1280*1280",
prompt_extend=True,
watermark=False,
seed=12345)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
return rsp
# Wait for the asynchronous task to finish
def wait_async_task(task):
rsp = ImageSynthesis.wait(task=task, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
# Save file to 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('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
# Fetch asynchronous task status
def fetch_task_status(task):
status = ImageSynthesis.fetch(task=task, api_key=api_key)
print(status)
if status.status_code == HTTPStatus.OK:
print(status.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(status.status_code, status.code, status.message))
# Cancel an asynchronous task. Only PENDING tasks can be canceled.
def cancel_task(task):
rsp = ImageSynthesis.cancel(task=task, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
async_call()
Exemplo de resposta
-
Resposta ao criar uma tarefa
{ "status_code": 200, "request_id": "31b04171-011c-96bd-ac00-f0383b669cc7", "code": "", "message": "", "output": { "task_id": "4f90cf14-a34e-4eae-xxxxxxxx", "task_status": "PENDING", "results": [] }, "usage": null } -
Resposta ao consultar resultados da tarefa
As URLs das imagens expiram após 24 horas. Baixe as imagens prontamente.
{ "status_code": 200, "request_id": "8ad45834-4321-44ed-adf5-xxxxxx", "code": null, "message": "", "output": { "task_id": "3aff9ebd-35fc-4339-98a3-xxxxxx", "task_status": "SUCCEEDED", "results": [ { "url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx", "orig_prompt": "Place the alarm clock from image 1 beside the vase on the dining table in image 2.", "actual_prompt": "Place the blue alarm clock from image 1 to the right of the vase on the dining table in image 2, near the edge of the tablecloth. Keep the clock facing the camera and parallel to the tabletop, with natural shadow projection." } ], "submit_time": "2025-10-23 16:18:16.009", "scheduled_time": "2025-10-23 16:18:16.040", "end_time": "2025-10-23 16:19:09.591", "task_metrics": { "TOTAL": 1, "FAILED": 0, "SUCCEEDED": 1 } }, "usage": { "image_count": 1 } }
Chamada via Java SDK
Certifique-se de que sua versão do DashScope Java SDK seja pelo menos 2.22.2.
Versões mais antigas podem gerar erros como “url error, please check url!”. Atualize usando Instalar ou atualizar SDK.
Chamada síncrona
Exemplo de solicitação
Este exemplo suporta três métodos de entrada de imagem: URL pública, codificação Base64 e caminho de arquivo local.
// 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.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class Image2Image {
static {
// The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If you have not configured an environment variable, replace the next line with: apiKey="sk-xxx"
// API keys differ between Singapore and Beijing. Get an API key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
/**
* Image input methods: choose one
*
* 1. Public URL — best for publicly accessible images
* 2. Local file — best for local development and testing
* 3. Base64 encoding — best for private images or secure transmission
*/
// [Method 1] Public URL
static String imageUrl_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp";
static String imageUrl_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp";
// [Method 2] Local file path (file://+absolute path or file:///+absolute path)
// static String imageUrl_1 = "file://" + "/your/path/to/image_1.png"; // Linux/macOS
// static String imageUrl_2 = "file:///" + "C:/your/path/to/image_2.png"; // Windows
// [Method 3] Base64 encoding
// static String imageUrl_1 = encodeFile("/your/path/to/image_1.png");
// static String imageUrl_2 = encodeFile("/your/path/to/image_2.png");
// List of images to edit
static List<String> imageUrls = new ArrayList<>();
static {
imageUrls.add(imageUrl_1);
imageUrls.add(imageUrl_2);
}
public static void syncCall() {
// Set parameters
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
parameters.put("seed", 12345);
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.5-i2i-preview")
.prompt("Place the alarm clock from image 1 beside the vase on the dining table in image 2.")
.images(imageUrls)
.n(1)
//.size("1280*1280")
.negativePrompt("")
.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));
}
/**
* Encode a file as a Base64 string
* @param filePath File path
* @return Base64 string in format data:{MIME_type};base64,{base64_data}
*/
public static String encodeFile(String filePath) {
Path path = Paths.get(filePath);
if (!Files.exists(path)) {
throw new IllegalArgumentException("File not found: " + filePath);
}
// Detect MIME type
String mimeType = null;
try {
mimeType = Files.probeContentType(path);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot detect file type: " + filePath);
}
if (mimeType == null || !mimeType.startsWith("image/")) {
throw new IllegalArgumentException("Unsupported or unrecognized image format");
}
// Read file and encode
byte[] fileBytes = null;
try{
fileBytes = Files.readAllBytes(path);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot read file: " + filePath);
}
String encodedString = Base64.getEncoder().encodeToString(fileBytes);
return "data:" + mimeType + ";base64," + encodedString;
}
public static void main(String[] args) {
syncCall();
}
}
Exemplo de resposta
As URLs das imagens expiram após 24 horas. Baixe as imagens prontamente.
{
"request_id": "d362685b-757f-4eac-bab5-xxxxxx",
"output": {
"task_id": "bfa7fc39-3d87-4fa7-b1e6-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"orig_prompt": "Place the alarm clock from image 1 beside the vase on the dining table in image 2.",
"actual_prompt": "Place the blue alarm clock from image 1 to the right of the vase on the dining table in image 2, near the edge of the tablecloth. Keep the clock facing the camera and parallel to the vase.",
"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"
}
],
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
}
},
"usage": {
"image_count": 1
}
}
Chamada assíncrona
Este exemplo usa URLs públicas para entrada de imagem.
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Image2Image {
static {
// The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If you have not configured an environment variable, replace the next line with: apiKey="sk-xxx"
// API keys differ between Singapore and Beijing. Get an API key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
// Public URLs
static String imageUrl_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp";
static String imageUrl_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp";
// List of images to edit
static List<String> imageUrls = new ArrayList<>();
static {
imageUrls.add(imageUrl_1);
imageUrls.add(imageUrl_2);
}
public static void asyncCall() {
// Set parameters
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
parameters.put("seed", 12345);
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.5-i2i-preview")
.prompt("Place the alarm clock from image 1 beside the vase on the dining table in image 2.")
.images(imageUrls)
.n(1)
//.size("1280*1280")
.negativePrompt("")
.parameters(parameters)
.build();
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
System.out.println("---async call, please wait a moment----");
result = imageSynthesis.asyncCall(param);
} catch (ApiException | NoApiKeyException e){
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
String taskId = result.getOutput().getTaskId();
System.out.println("taskId=" + taskId);
try {
result = imageSynthesis.wait(taskId, apiKey);
} catch (ApiException | NoApiKeyException e){
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
System.out.println(JsonUtils.toJson(result.getOutput()));
}
public static void listTask() throws ApiException, NoApiKeyException {
ImageSynthesis is = new ImageSynthesis();
AsyncTaskListParam param = AsyncTaskListParam.builder().build();
param.setApiKey(apiKey);
ImageSynthesisListResult result = is.list(param);
System.out.println(result);
}
public void fetchTask(String taskId) throws ApiException, NoApiKeyException {
ImageSynthesis is = new ImageSynthesis();
// If DASHSCOPE_API_KEY is set as an environment variable, apiKey can be empty.
ImageSynthesisResult result = is.fetch(taskId, apiKey);
System.out.println(result.getOutput());
System.out.println(result.getUsage());
}
public static void main(String[] args) {
asyncCall();
}
}
Exemplo de resposta
-
Resposta ao criar uma tarefa
{ "request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8", "output": { "task_id": "7277e20e-aa01-4709-xxxxxxxx", "task_status": "PENDING" } } -
Resposta ao consultar resultados da tarefa
As URLs das imagens expiram após 24 horas. Baixe as imagens prontamente.
{ "request_id": "d362685b-757f-4eac-bab5-xxxxxx", "output": { "task_id": "bfa7fc39-3d87-4fa7-b1e6-xxxxxx", "task_status": "SUCCEEDED", "results": [ { "orig_prompt": "Place the alarm clock from image 1 beside the vase on the dining table in image 2.", "actual_prompt": "Place the blue alarm clock from image 1 to the right of the vase on the dining table in image 2, near the edge of the tablecloth. Keep the clock facing the camera and parallel to the vase.", "url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx" } ], "task_metrics": { "TOTAL": 1, "SUCCEEDED": 1, "FAILED": 0 } }, "usage": { "image_count": 1 } }
Limites
Retenção de dados: Tanto os IDs de tarefa quanto as URLs de imagens expiram após 24 horas. Você não pode consultá-los ou baixá-los após a expiração.
Moderação de conteúdo: Todos os prompts, imagens de entrada e imagens de saída passam por moderação de conteúdo. Solicitações contendo conteúdo proibido retornam erros como “IPInfringementSuspect” ou “DataInspectionFailed”. Consulte Informações de erro para detalhes.
Códigos de erro
Se a chamada do modelo falhar e retornar uma mensagem de erro, consulte Códigos de erro para resolução.
FAQ
P: Eu usei o General Image Editing 2.1 anteriormente. Preciso alterar minhas chamadas de SDK para usar o wan2.5?
R: Sim — o design dos parâmetros difere entre as versões:
General Image Editing 2.1: Requer ambos os parâmetros
promptefunction.General Image Editing 2.5: Requer apenas
prompt. Descreva todas as edições em texto. O parâmetrofunctionnão é mais suportado nem necessário.
P: Como visualizo as métricas de uso do modelo?
R: Uma hora após a conclusão de uma chamada de modelo, acesse a página Model telemetry (Singapore)Model telemetry (Beijing) para visualizar métricas como contagem de chamadas e taxa de sucesso. Para orientações passo a passo, consulte Como visualizar o histórico de chamadas do modelo?.



