El modelo de imagen a video Wan genera un video fluido a partir de una imagen de primer fotograma y un prompt de texto.
Documentos relacionados: Guía del usuario
NotaWan 2.7 - imagen a video admite de primer fotograma a video, de primer y último fotograma a video, y continuación de video. Recomendamos esta versión.
La función imagen a video (basada en el primer fotograma) para modelos Wan 2.6 y anteriores solo admite de primer fotograma a video.
Disponibilidad
Su modelo, URL de endpoint y clave de API deben estar en la misma región. Las llamadas entre regiones fallarán.
- Seleccionar un modelo: Confirm la región donde está disponible el modelo.
- Seleccionar una URL: Seleccione la URL de endpoint para la región correspondiente. Se admiten tanto URLs HTTP como del SDK de DashScope.
- Configurar una clave de API: Obtenga una clave de API para la región y luego configure la clave de API en sus variables de entorno.
- Instalar el SDK: Para realizar llamadas con el SDK, instale el SDK de DashScope.
NotaEl código de ejemplo en este tema corresponde a la región de Singapur.
ImportanteAlibaba Cloud Model Studio ha lanzado dominios específicos de espacio de trabajo para las regiones de China (Beijing) y Singapur. Los nuevos dominios dedicados ofrecen un rendimiento superior y una mayor estabilidad para las solicitudes de inferencia. Recomendamos migrar a los nuevos dominios:
- China (Pekín): de
https://dashscope.aliyuncs.comahttps://{WorkspaceId}.cn-beijing.maas.aliyuncs.com - Singapur: de
https://dashscope-intl.aliyuncs.comahttps://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
{WorkspaceId} es su ID de espacio de trabajo, que se encuentra en la página Workspace Details de la consola de Alibaba Cloud Model Studio. El dominio existente permanece totalmente funcional.
Llamada HTTP
Las tareas de imagen a video utilizan invocación asíncrona (típicamente 1–5 minutos): crear tarea -> sondear resultados.
Paso 1: Crear una tarea
Singapore
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis
Virginia
POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis
Beijing
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis
Fráncfort
POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis
Reemplace {WorkspaceId} con su ID de espacio de trabajo real.
Nota
- Después de crear la tarea, utilice el
task_iddevuelto para consultar el resultado. Eltask_ides válido durante 24 horas. No cree tareas duplicadas. En su lugar, utilice el sondeo para recuperar el resultado. - Para obtener orientación para principiantes, consulte Llamar a APIs con Postman o cURL.
Parámetros de solicitudEncabezadosContent-Type El tipo de contenido de la solicitud. Debe ser Authorization Autentica la solicitud con una clave API de Model Studio. Ejemplo: Bearer sk-xxxx. X-DashScope-Async Habilita el procesamiento asíncrono. Las solicitudes HTTP solo admiten llamadas asíncronas. Debe ser ImportanteSi falta este encabezado de solicitud, se devuelve el error "current user api does not support synchronous calls". Cuerpo de la solicitudmodel El nombre del modelo. Modelos disponibles y precios: precios de modelos. Ejemplo: wan2.6-i2v-flash. input Campos de entrada que incluyen el prompt. parameters Controles para resolución, duración, reescritura inteligente de prompts y marcas de agua. | Narrativa de múltiples tomasEsta función solo es compatible con los modelos de la serie Wan2.6. Puede habilitarlo configurando Doblaje automáticoEsta función solo es compatible con los modelos de las series Wan2.6 y Wan2.5. Si no proporciona Audio personalizadoEsta función solo es compatible con los modelos de las series Wan2.6 y Wan2.5. Para especificar música de fondo o una voz en off para el video, pase la URL de su archivo de audio personalizado en el parámetro Video silenciosoSolo los siguientes modelos admiten la generación de video silencioso:
Prompt negativoUtilice el parámetro negative_prompt para evitar que aparezcan "flores" en el video generado. |
Parámetros de respuestaoutput Información sobre la salida de la tarea. request_id Identificador único de solicitud para rastreo y solución de problemas. code Código de error. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error. message Mensaje de error detallado. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error. | Respuesta exitosaGuarde el Respuesta de errorError en la creación de la tarea. Consulte Códigos de error. |
Paso 2: Consultar el resultado de la tarea
Singapore
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Virginia
GET https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
China (Beijing)
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
Fráncfort
GET https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Reemplace {WorkspaceId} con su ID de espacio de trabajo real.
Nota
- Recomendación de sondeo: La generación de video tarda varios minutos. Utilice un mecanismo de sondeo con un intervalo razonable, como 15 segundos.
- Transición de estado de la tarea: PENDING → RUNNING → SUCCEEDED o FAILED.
- Enlace de resultado: Después de que una tarea tenga éxito, se devuelve una URL de video válida durante 24 horas. Descargue y guarde el video en un almacenamiento permanente, como OSS.
task_idvalidez: 24 horas. Después de este período, las consultas devuelven el estado de la tarea comoUNKNOWN.
Parámetros de solicitudEncabezadosAuthorization Autentica la solicitud con una clave API de Model Studio. Ejemplo: Bearer sk-xxxx. Parámetros de rutatask_id El ID de la tarea. | Consultar resultado de la tareaReemplace |
Parámetros de respuestaoutput Los detalles de salida de la tarea. usage Estadísticas de uso de la tarea, que se contabilizan únicamente para tareas exitosas. request_id Identificador único de solicitud para rastreo y solución de problemas. | Tarea exitosaLas URL de video son válidas solo durante 24 horas y luego se eliminan automáticamente. Guarde los videos generados de inmediato. Tarea fallidaCuando una tarea falla, Consulta de tarea caducadaEl |
Llamadas del SDK de DashScope
Los nombres de los parámetros del SDK son en gran medida consistentes con la API HTTP, siguiendo las convenciones de cada lenguaje.
Las tareas de imagen a video suelen tardar 1–5 minutos. El SDK encapsula el proceso de llamada HTTP asíncrona y admite tanto llamadas síncronas como asíncronas.
El tiempo de procesamiento depende de la cola de tareas y del estado del servicio.
SDK de Python
ImportanteAsegúrese de que su versión del SDK de Python de DashScope sea al menos1.25.8 antes de ejecutar el siguiente código.
Las versiones anteriores podrían provocar errores como "url error, please check url!". Para actualizar, consulte Instalar el SDK.
Establezca base_http_api_url según la región del modelo:
Singapore
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
Virginia
dashscope.base_http_api_url = 'https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1'
Beijing
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'
Fráncfort
dashscope.base_http_api_url = 'https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1'
Reemplace {WorkspaceId} con su ID de espacio de trabajo real.
Código de ejemplo
Llamada síncrona
Una llamada síncrona se bloquea hasta que finaliza la generación del video. Este ejemplo demuestra tres métodos de entrada de imagen: URL pública, codificación Base64 y ruta de archivo local.
Ejemplo de solicitud
import base64
import os
from http import HTTPStatus
from dashscope import VideoSynthesis
import mimetypes
import dashscope
# 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 the environment variable is not set, replace the following line with your API key from Model Studio: api_key="sk-xxx"
# Get your API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# --- Helper function for Base64 encoding ---
# 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:
The following are three ways to provide an image. Choose one.
1. Public URL: Ideal for images that are already publicly accessible.
2. Local file: Suitable for local development and testing.
3. Base64 encoding: Best for private images or when data must be securely transmitted.
"""
# [Method 1] Use a publicly accessible image URL
# Example: Use a public image URL
img_url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png"
# [Method 2] Use a local file (supports absolute and relative paths)
# Format: file:// + file path
# Example (absolute path):
# img_url = "file://" + "/path/to/your/img.png" # Linux/macOS
# img_url = "file://" + "C:/path/to/your/img.png" # Windows
# Example (relative path):
# img_url = "file://" + "./img.png" # Relative to the current script's directory
# [Method 3] Use a Base64-encoded image
# img_url = encode_file("./img.png")
# Set the audio URL
audio_url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/ozwpvi/rap.mp3"
def sample_call_i2v():
# A synchronous call returns the result directly.
print('please wait...')
rsp = VideoSynthesis.call(api_key=api_key,
model='wan2.6-i2v-flash',
prompt='A scene of urban fantasy art. A dynamic graffiti art character. A boy made of spray paint comes to life from a concrete wall. He raps an English song at high speed while striking a classic, energetic rapper pose. The scene is set under an urban railway bridge at night. The lighting comes from a single street lamp, creating a cinematic atmosphere full of high energy and amazing detail. The audio of the video consists entirely of his rap, with no other dialogue or noise.',
img_url=img_url,
audio_url=audio_url,
resolution="720P",
duration=10,
prompt_extend=True,
watermark=False,
negative_prompt="",
seed=12345)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print("video_url:", rsp.output.video_url)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
sample_call_i2v()
Ejemplo de respuesta
El video_url es válido durante 24 horas. Descargue el video antes de que caduque.
{
"status_code": 200,
"request_id": "2794c7a3-fe8c-4dd4-a1b7-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "c15d5b14-07c4-4af5-b862-xxxxxx",
"task_status": "SUCCEEDED",
"video_url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxx.mp4?Expires=xxx",
"submit_time": "2026-01-22 23:24:46.527",
"scheduled_time": "2026-01-22 23:24:46.565",
"end_time": "2026-01-22 23:25:59.978",
"orig_prompt": "A scene of urban fantasy art. A dynamic graffiti art character. A boy made of spray paint comes to life from a concrete wall. He raps an English song at high speed while striking a classic, energetic rapper pose. The scene is set under an urban railway bridge at night. The lighting comes from a single street lamp, creating a cinematic atmosphere full of high energy and amazing detail. The audio of the video consists entirely of his rap, with no other dialogue or noise."
},
"usage": {
"video_count": 1,
"video_duration": 0,
"video_ratio": "",
"duration": 10,
"input_video_duration": 0,
"output_video_duration": 10,
"audio": true,
"SR": 720
}
}
Llamada asíncrona
Una llamada asíncrona devuelve inmediatamente un ID de tarea. Luego puede sondear el resultado o esperar a que finalice.
Ejemplo de solicitud
import os
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope
# 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 the environment variable is not set, replace the following line with your API key from Model Studio: api_key="sk-xxx"
# Get your API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# Use a publicly accessible image URL
img_url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png"
# Set the audio URL
audio_url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/ozwpvi/rap.mp3"
def sample_async_call_i2v():
# Asynchronous call, returns a task ID
rsp = VideoSynthesis.async_call(api_key=api_key,
model='wan2.6-i2v-flash',
prompt='A scene of urban fantasy art. A dynamic graffiti art character. A boy made of spray paint comes to life from a concrete wall. He raps an English song at high speed while striking a classic, energetic rapper pose. The scene is set under an urban railway bridge at night. The lighting comes from a single street lamp, creating a cinematic atmosphere full of high energy and amazing detail. The audio of the video consists entirely of his rap, with no other dialogue or noise.',
img_url=img_url,
audio_url=audio_url,
resolution="720P",
duration=10,
prompt_extend=True,
watermark=False,
negative_prompt="",
seed=12345)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print("task_id: %s" % rsp.output.task_id)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
# Get the status of the asynchronous task
status = VideoSynthesis.fetch(task=rsp, api_key=api_key)
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))
# Wait for the asynchronous task to complete
rsp = VideoSynthesis.wait(task=rsp, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.video_url)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
sample_async_call_i2v()
Ejemplo de respuesta
- Respuesta de creación de tarea
{
"status_code": 200,
"request_id": "6dc3bf6c-be18-9268-9c27-xxxxxx",
"code": "",
"message": "",
"output": {
"task_id": "686391d9-7ecf-4290-a8e9-xxxxxx",
"task_status": "PENDING",
"video_url": ""
},
"usage": null
}
- Respuesta de consulta de tarea
El video_url es válido durante 24 horas. Descargue el video antes de que caduque.
{
"status_code": 200,
"request_id": "2794c7a3-fe8c-4dd4-a1b7-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "c15d5b14-07c4-4af5-b862-xxxxxx",
"task_status": "SUCCEEDED",
"video_url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxx.mp4?Expires=xxx",
"submit_time": "2026-01-22 23:24:46.527",
"scheduled_time": "2026-01-22 23:24:46.565",
"end_time": "2026-01-22 23:25:59.978",
"orig_prompt": "A scene of urban fantasy art. A dynamic graffiti art character. A boy made of spray paint comes to life from a concrete wall. He raps an English song at high speed while striking a classic, energetic rapper pose. The scene is set under an urban railway bridge at night. The lighting comes from a single street lamp, creating a cinematic atmosphere full of high energy and amazing detail. The audio of the video consists entirely of his rap, with no other dialogue or noise."
},
"usage": {
"video_count": 1,
"video_duration": 0,
"video_ratio": "",
"duration": 10,
"input_video_duration": 0,
"output_video_duration": 10,
"audio": true,
"SR": 720
}
}
SDK de Java
ImportanteAsegúrese de que su versión del SDK de Java de DashScope sea al menos2.22.6 antes de ejecutar el siguiente código.
Las versiones anteriores podrían provocar errores como "url error, please check url!". Para actualizar, consulte Instalar el SDK.
Establezca baseHttpApiUrl según la región del modelo:
Singapore
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
Virginia
Constants.baseHttpApiUrl = "https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1";
Beijing
Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
Fráncfort
Constants.baseHttpApiUrl = "https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1";
Reemplace {WorkspaceId} con su ID de espacio de trabajo real.
Código de ejemplo
Llamada síncrona
Una llamada síncrona se bloquea hasta que finaliza la generación del video. Este ejemplo demuestra tres métodos de entrada de imagen: URL pública, codificación Base64 y ruta de archivo local.
Ejemplo de solicitud
// Copyright (c) Alibaba, Inc. and its affiliates.
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesis;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisParam;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
public class Image2Video {
static {
// Set the endpoint. This example uses the Singapore region. For other regions, see: https://www.alibabacloud.com/help/model-studio/image-to-video-api-reference
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If the environment variable is not set, replace the following line with your API key from Model Studio: apiKey="sk-xxx"
// Get your API key: https://www.alibabacloud.com/help/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
/**
* Image input methods: Choose one of the following three.
*
* 1. Public URL: Ideal for images that are already publicly accessible.
* 2. Local file: Suitable for local development and testing.
* 3. Base64 encoding: Best for private images or when data must be securely transmitted.
*/
// [Method 1] Public URL
static String imgUrl = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png";
// [Method 2] Local file path (file:// + absolute path)
// static String imgUrl = "file://" + "/your/path/to/img.png"; // Linux/macOS
// static String imgUrl = "file://" + "C:/your/path/to/img.png"; // Windows
// [Method 3] Base64 encoding
// static String imgUrl = Image2Video.encodeFile("/your/path/to/img.png");
// Set the audio URL
static String audioUrl = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/ozwpvi/rap.mp3";
public static void image2video() throws ApiException, NoApiKeyException, InputRequiredException {
// Set the parameters
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
parameters.put("seed", 12345);
VideoSynthesis vs = new VideoSynthesis();
VideoSynthesisParam param =
VideoSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.6-i2v-flash")
.prompt("A scene of urban fantasy art. A dynamic graffiti art character. A boy made of spray paint comes to life from a concrete wall. He raps an English song at high speed while striking a classic, energetic rapper pose. The scene is set under an urban railway bridge at night. The lighting comes from a single street lamp, creating a cinematic atmosphere full of high energy and amazing detail. The audio of the video consists entirely of his rap, with no other dialogue or noise.")
.imgUrl(imgUrl)
.audioUrl(audioUrl)
.duration(10)
.parameters(parameters)
.resolution("720P")
.negativePrompt("")
.build();
System.out.println("please wait...");
VideoSynthesisResult result = vs.call(param);
System.out.println(JsonUtils.toJson(result));
}
/**
* Encodes a file into a Base64 string.
* @param filePath The file path.
* @return A Base64 string in the 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 does not exist: " + 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 content and encode
byte[] fileBytes = null;
try{
fileBytes = Files.readAllBytes(path);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot read file content: " + filePath);
}
String encodedString = Base64.getEncoder().encodeToString(fileBytes);
return "data:" + mimeType + ";base64," + encodedString;
}
public static void main(String[] args) {
try {
image2video();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
Ejemplo de respuesta
El video_url es válido durante 24 horas. Descargue el video antes de que caduque.
{
"request_id": "87c091bb-7a3c-4904-8501-xxxxxx",
"output": {
"task_id": "413ed6e4-5f3a-4f57-8d58-xxxxxx",
"task_status": "SUCCEEDED",
"video_url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxx.mp4?Expires=xxx",
"orig_prompt": "A scene of urban fantasy art. A dynamic graffiti art character. A boy made of spray paint comes to life from a concrete wall. He raps an English song at high speed while striking a classic, energetic rapper pose. The scene is set under an urban railway bridge at night. The lighting comes from a single street lamp, creating a cinematic atmosphere full of high energy and amazing detail. The audio of the video consists entirely of his rap, with no other dialogue or noise.",
"submit_time": "2026-01-22 23:25:45.729",
"scheduled_time": "2026-01-22 23:25:45.771",
"end_time": "2026-01-22 23:26:44.942"
},
"usage": {
"video_count": 1,
"duration": 10.0,
"input_video_duration": 0.0,
"output_video_duration": 10.0,
"SR": "720"
},
"status_code": 200,
"code": "",
"message": ""
}
Llamada asíncrona
Una llamada asíncrona devuelve inmediatamente un ID de tarea. Luego puede sondear el resultado o esperar a que finalice.
Ejemplo de solicitud
// Copyright (c) Alibaba, Inc. and its affiliates.
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesis;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisListResult;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisParam;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
import java.util.HashMap;
import java.util.Map;
public class Image2Video {
static {
// Set the endpoint. This example uses the Singapore region. For other regions, see: https://www.alibabacloud.com/help/model-studio/image-to-video-api-reference
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If the environment variable is not set, replace the following line with your API key from Model Studio: apiKey="sk-xxx"
// Get your API key: https://www.alibabacloud.com/help/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
// Set the input image URL
static String imgUrl = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png";
// Set the audio URL
static String audioUrl = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/ozwpvi/rap.mp3";
public static void image2video() throws ApiException, NoApiKeyException, InputRequiredException {
// Set the parameters
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
parameters.put("seed", 12345);
VideoSynthesis vs = new VideoSynthesis();
VideoSynthesisParam param =
VideoSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.6-i2v-flash")
.prompt("A scene of urban fantasy art. A dynamic graffiti art character. A boy made of spray paint comes to life from a concrete wall. He raps an English song at high speed while striking a classic, energetic rapper pose. The scene is set under an urban railway bridge at night. The lighting comes from a single street lamp, creating a cinematic atmosphere full of high energy and amazing detail. The audio of the video consists entirely of his rap, with no other dialogue or noise.")
.imgUrl(imgUrl)
.audioUrl(audioUrl)
.duration(10)
.parameters(parameters)
.resolution("720P")
.negativePrompt("")
.build();
// Asynchronous call
VideoSynthesisResult task = vs.asyncCall(param);
System.out.println(JsonUtils.toJson(task));
System.out.println("please wait...");
// Get the result
VideoSynthesisResult result = vs.wait(task, apiKey);
System.out.println(JsonUtils.toJson(result));
}
// Get the task list
public static void listTask() throws ApiException, NoApiKeyException {
VideoSynthesis is = new VideoSynthesis();
AsyncTaskListParam param = AsyncTaskListParam.builder().build();
param.setApiKey(apiKey);
VideoSynthesisListResult result = is.list(param);
System.out.println(result);
}
// Get the result of a single task
public static void fetchTask(String taskId) throws ApiException, NoApiKeyException {
VideoSynthesis is = new VideoSynthesis();
// If DASHSCOPE_API_KEY is set as an environment variable, apiKey can be null.
VideoSynthesisResult result = is.fetch(taskId, apiKey);
System.out.println(result.getOutput());
System.out.println(result.getUsage());
}
public static void main(String[] args) {
try {
image2video();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
Ejemplo de respuesta
- Respuesta de creación de tarea
{
"request_id": "5dbf9dc5-4f4c-9605-85ea-xxxxxxxx",
"output": {
"task_id": "7277e20e-aa01-4709-xxxxxxxx",
"task_status": "PENDING"
}
}
- Respuesta de consulta de tarea
El video_url es válido durante 24 horas. Descargue el video antes de que caduque.
{
"request_id": "87c091bb-7a3c-4904-8501-xxxxxx",
"output": {
"task_id": "413ed6e4-5f3a-4f57-8d58-xxxxxx",
"task_status": "SUCCEEDED",
"video_url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxx.mp4?Expires=xxx",
"orig_prompt": "A scene of urban fantasy art. A dynamic graffiti art character. A boy made of spray paint comes to life from a concrete wall. He raps an English song at high speed while striking a classic, energetic rapper pose. The scene is set under an urban railway bridge at night. The lighting comes from a single street lamp, creating a cinematic atmosphere full of high energy and amazing detail. The audio of the video consists entirely of his rap, with no other dialogue or noise.",
"submit_time": "2026-01-22 23:25:45.729",
"scheduled_time": "2026-01-22 23:25:45.771",
"end_time": "2026-01-22 23:26:44.942"
},
"usage": {
"video_count": 1,
"duration": 10.0,
"input_video_duration": 0.0,
"output_video_duration": 10.0,
"SR": "720"
},
"status_code": 200,
"code": "",
"message": ""
}
Limitaciones
- Retención de datos: El
task_idy la URL del video se conservan durante 24 horas. Después de este periodo, no podrá consultarlos ni descargarlos. - Moderación de contenido: Todas las entradas (prompts, imágenes) y los videos de salida están sujetos a moderación de contenido. Las infracciones resultan en un error
IPInfringementSuspectoDataInspectionFailed. Códigos de error.
Limitaciones conocidas
Cuando wan2.6-i2v-flash genera una rotación continua de un objeto circular (como un anillo, un engranaje o la esfera de un reloj), el video puede detenerse durante aproximadamente 1 segundo alrededor de la marca de 3 segundos. Para evitar este problema, utilice el modelo Wan 2.7 - imagen a video en su lugar.
Códigos de error
Si una llamada al modelo devuelve un mensaje de error, consulte Códigos de error.
FAQ
P: ¿Cómo generar un video con una relación de aspecto específica?
R: La imagen de primer fotograma de entrada (img_url) determina la relación de aspecto del video de salida. Sin embargo, no se garantiza una relación exacta como 3:4, ya que pueden ocurrir desviaciones menores.
-
¿Por qué ocurren desviaciones?
El modelo utiliza la relación de aspecto de la imagen de entrada como línea base y la combina con el recuento total de píxeles del nivel de resolución seleccionado (
resolution) para calcular la resolución válida más cercana. Dado que el ancho y la altura de un video deben ser múltiplos de 16, el modelo ajusta la resolución final en consecuencia. Como resultado, no se garantiza que la relación de aspecto de salida sea exactamente 3:4, pero será muy cercana.- Por ejemplo, una imagen de entrada de 750×1000 (relación de aspecto 3:4 = 0.75) con
resolutionestablecido en "720P" (un objetivo de aproximadamente 920,000 píxeles totales) produce una salida de 816×1104 (relación de aspecto ≈ 0.739, aproximadamente 900,000 píxeles totales).
- Por ejemplo, una imagen de entrada de 750×1000 (relación de aspecto 3:4 = 0.75) con
-
Recomendaciones:
- Controlar la entrada: Para obtener mejores resultados, utilice una imagen de primer fotograma que ya tenga su relación de aspecto objetivo.
- Posprocesamiento: Si necesita una relación de aspecto estricta, recorte el video o agregue barras negras utilizando una herramienta de edición después de la generación.
P: ¿Cómo obtener la lista de permitidos de dominios de almacenamiento de video?
R: Los videos generados por los modelos se almacenan en OSS. La API devuelve una URL pública temporal. Para configurar una lista blanca de firewall para esta URL de descarga, tenga en cuenta lo siguiente: El almacenamiento subyacente puede cambiar dinámicamente. Este tema no proporciona una lista blanca fija de nombres de dominio de OSS para evitar problemas de acceso causados por información obsoleta. Si tiene requisitos de control de seguridad, póngase en contacto con su gerente de cuenta para obtener la lista más reciente de nombres de dominio de OSS.