Wan -image-to-video-first and last frames API reference(2.2)

Updated at:

The Wan 2.2 model generates a smoothly transitioning video from a first frame , a last frame, and a text prompt .

Related documents: User guide

Usage notes

To ensure successful API calls, your model, endpoint URL, and API key must be in the same region. Cross-region calls will fail.

NoteThe code examples in this topic apply to China (Beijing).

ImportantAlibaba Cloud Model Studio has released workspace-specific domains for the China (Beijing) and Singapore regions. The new dedicated domains deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:

  • China (Beijing): from https://dashscope.aliyuncs.com to https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapore: from https://dashscope-intl.aliyuncs.com to https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

{WorkspaceId} is your workspace ID, which can be found on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domain remains fully functional.

HTTP call

Because image-to-video tasks are long-running operations that typically take 1 to 5 minutes, the API uses an asynchronous call. The process involves two core steps: create a task, then poll for the result.

Step 1: Create a task to obtain the task ID

China (Beijing)

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image2video/video-synthesis

Replace {WorkspaceId} with your actual workspace ID.

Singapore

POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image2video/video-synthesis

Replace {WorkspaceId} with your actual workspace ID.

Note

  • After the task is created successfully, use the task_id returned by the API to query the result. The task_id is valid for 24 hours. Do not create duplicate tasks; simply use polling to obtain the result.

Request parameters

Request headers

Content-Type string (Required)

The content type of the request. Must be application/json.

Authorization string (Required)

Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.

X-DashScope-Async string (Required)

Enables asynchronous processing. HTTP requests support only asynchronous calls. Must be set to enable.

ImportantIf this request header is missing, the error "current user api does not support synchronous calls" is returned.

Request body

model string (Required)

The name of the model. Example: wan2.2-kf2v-flash.

For details, see the Model Studio console.

input object (Required)

Contains the primary input for the task, such as the prompt.

Properties

prompt string (Optional)

The text prompt. Supports both Chinese and English. The maximum length is 800 characters. Both Chinese characters and letters count as a single character. Text exceeding this limit is truncated.

If there are significant changes in the subject or scene between the first and last frames, we recommend describing the transition process, such as camera movement (e.g., "camera moves to the left") or subject movement (e.g., "a person runs forward").

Example: "A small black cat looks up at the sky curiously. The camera gradually rises from eye level and finally captures its curious gaze from a top-down view."

For tips on writing effective prompts, see the Prompt guide for text-to-video and image-to-video.

negative_prompt string (Optional)

A negative prompt that describes content to exclude from the video, which helps constrain the output.

Supports both Chinese and English. The maximum length is 500 characters. Text exceeding this limit is truncated.

Example: "low resolution, error, worst quality, low quality, deformed, extra fingers, bad proportions".

first_frame_url string (Required)

The URL or Base64-encoded data of the first frame image. The aspect ratio of the output video is determined by this image.

Image requirements:

  • Image format: JPEG, JPG, PNG (transparent channels not supported), BMP, WEBP.
  • Image resolution: The width and height of the image range from [240,8000], in pixels.
  • File size: no more than 10MB.

Supported input formats:

  1. Public URL:

  2. Temporary URL:

  3. Base64-encoded string:

    • Data format: data:{MIME_type};base64,{base64_data}
    • Example: data:image/png;base64,GDU7MtCZzEbTbmRZ...... (The encoded string is truncated for brevity.)
    • For details, see How to input images.

last_frame_url string (Optional)

The URL or Base64-encoded data of the last frame image.

Image requirements:

  • Image format: JPEG, JPG, PNG (transparent channels not supported), BMP, WEBP.
  • Image resolution: The width and height of the image range from [240,8000], in pixels. The last frame image resolution can differ from the first frame image resolution; forced alignment is not required.
  • File size: no more than 10MB.

Supported input formats:

  1. Public URL:

  2. Temporary URL:

  3. Base64-encoded string:

    • Data format: data:{MIME_type};base64,{base64_data}
    • Example: data:image/png;base64,GDU7MtCZ...... (The encoded string is truncated for brevity.)
    • For details, see How to input images.

template string (Optional)

The name of the video effect template. When you use this parameter, you only need to provide first_frame_url.

Different models support different effect templates. To avoid call failures, refer to the Wan image-to-video effect list before making a call.

Example: hufu-1, which applies the "Tang Rhyme" effect.

parameters object (Optional)

Video processing parameters.

Properties

resolution string (Optional)

ImportantThe resolution parameter directly affects the cost. For the same model, the cost hierarchy is 1080P > 720P > 480P. Confirm the pricing in the Model Studio console before making a call.

The resolution tier of the generated video. This parameter only adjusts the definition (total pixels) of the video without changing its aspect ratio. The video's aspect ratio will match that of the first frame image (first_frame_url).

The default value and available values for this parameter depend on the model parameter, as described below:

  • wan2.2-kf2v-flash: valid values: 480P, 720P, 1080P. Default value is 720P.
  • wanx2.1-kf2v-plus: valid value: 720P. Default value is 720P.

Example: 720P

duration integer (Optional)

ImportantThe duration parameter directly affects the cost, which is billed per second. Confirm the pricing in the Model Studio console before making a call.

The duration of the generated video, in seconds. The current value is fixed at 5 and cannot be changed. The model always generates 5-second videos.

prompt_extendbool (Optional)

Specifies whether to enable prompt rewriting. When enabled, a large language model (LLM) intelligently rewrites the input prompt. This can significantly improve results for short prompts but increases latency.

  • true: Default value. Enables prompt rewriting.
  • false: Disables prompt rewriting.

Example: true

watermark bool (Optional)

Specifies whether to add a watermark to the bottom-right corner of the image, with the text "AI-generated".

  • false: Default value. Does not add a watermark.
  • true: Adds a watermark.

Example: false

seed integer (Optional)

The random number seed must be an integer in the range [0, 2147483647].

If not specified, a random seed is generated. A fixed seed improves reproducibility.

Because model generation is probabilistic, the same seed does not guarantee identical results.

First and last frames

Generates a video based on a first frame, a last frame, and a prompt.

# 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image2video/video-synthesis' \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wan2.2-kf2v-flash",
    "input": {
        "first_frame_url": "https://wanx.alicdn.com/material/20250318/first_frame.png",
        "last_frame_url": "https://wanx.alicdn.com/material/20250318/last_frame.png",
        "prompt": "写实风格,一只黑色小猫好奇地看向天空,镜头从平视逐渐上升,最后俯拍它的好奇的眼神。"
    },
    "parameters": {
        "resolution": "480P",
        "prompt_extend": true
    }
}'

Base64 encoding

The first_frame_url and last_frame_url parameters support Base64-encoded image strings. Download the first_frame_base64 and last_frame_base64 files and paste their full content into the corresponding parameters.

For format details, see How to input images.

# 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image2video/video-synthesis' \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wanx2.1-kf2v-plus",
    "input": {
        "first_frame_url": "data:image/png;base64,GDU7MtCZzEbTbmRZ......",
        "last_frame_url": "data:image/png;base64,VBORw0KGgoAAAANSUh......",
        "prompt": "写实风格,一只黑色小猫好奇地看向天空,镜头从平视逐渐上升,最后俯拍它的好奇的眼神。"
    },
    "parameters": {
        "resolution": "720P",
        "prompt_extend": true
    }
}'

Video effects

You must provide the first_frame_url and template parameters. The prompt and last_frame_url parameters are not required.

Different models support different effect templates. To avoid call failures, refer to the Wan image-to-video effect list before making a call.

# 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image2video/video-synthesis' \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wanx2.1-kf2v-plus",
    "input": {
        "first_frame_url": "https://ty-yuanfang.oss-cn-hangzhou.aliyuncs.com/lizhengjia.lzj/tmp/11.png",
        "template": "hanfu-1"
    },
    "parameters": {
        "resolution": "720P",
        "prompt_extend": true
    }
}'

Negative prompt

Use the negative_prompt parameter to exclude certain elements, such as people, from the generated video.

# 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image2video/video-synthesis' \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wanx2.1-kf2v-plus",
    "input": {
        "first_frame_url": "https://wanx.alicdn.com/material/20250318/first_frame.png",
        "last_frame_url": "https://wanx.alicdn.com/material/20250318/last_frame.png",
        "prompt": "写实风格,一只黑色小猫好奇地看向天空,镜头从平视逐渐上升,最后俯拍它的好奇的眼神。",
        "negative_prompt": "人物"
    },
    "parameters": {
        "resolution": "720P",
        "prompt_extend": true
    }
}'

Response parameters

output object

The output information for the task.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The status of the task.

Enumeration values

  • PENDING: The task is queuing.
  • RUNNING: The task is being processed.
  • SUCCEEDED: The task completed successfully.
  • FAILED: The task failed.
  • CANCELED: The task was canceled.
  • UNKNOWN: The task does not exist or its status is unknown.

request_idstring

Unique request identifier for tracing and troubleshooting.

codestring

Error code. Returned only for failed requests. See Error codes.

messagestring

Detailed error message. Returned only for failed requests. See Error codes.

Successful response

Please save the task_id, which is used to query the task status and results.

{
    "output": {
        "task_status": "PENDING",
        "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
    },
    "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}

Error response

Task creation failed. See Error codes.

{
    "code": "InvalidApiKey",
    "message": "No API-key provided.",
    "request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
}

Step 2: Query the result by task ID

China (Beijing)

GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}

Replace {WorkspaceId} with your actual workspace ID.

Singapore

GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

Replace {WorkspaceId} with your actual workspace ID.

Note

  • Polling recommendation: Video generation takes several minutes. It is recommended to adopt a polling mechanism and set a reasonable query interval (for example, 15 seconds) to obtain the result.
  • Task status transitions: PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
  • Result link: When the task succeeds, a video link is returned, valid for 24 hours. We recommend downloading it immediately after obtaining the link and transferring it to permanent storage (such as Alibaba Cloud OSS).
  • task_id validity: 24 hours. After it expires, the result can no longer be queried, and the API will return the task status as UNKNOWN.
  • RPS limit: The default RPS of the query API is 20. For higher-frequency queries or event notifications, we recommend configuring asynchronous task callbacks.
  • More operations: For batch queries, task cancellation, and other operations, see Manage asynchronous tasks.

Request parameters

Request headers

Authorization string (Required)

Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.

Path parameters

task_id string (Required)

The ID of the task.

Query task result

Please replace 86ecf553-d340-4e21-xxxxxxxxx with the actual task_id.

If you use a model in the Singapore (Singapore) region, you need to replace base_url with https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx, where {WorkspaceId} must be replaced with the actual workspace ID.

curl -X GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

Response parameters

outputobject

The output information for the task.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The status of the task.

Enumeration values

  • PENDING: The task is queuing.
  • RUNNING: The task is being processed.
  • SUCCEEDED: The task completed successfully.
  • FAILED: The task failed.
  • CANCELED: The task was canceled.
  • UNKNOWN: The task does not exist or its status is unknown.
State transitions during polling:
  • PENDING → RUNNING → SUCCEEDED or FAILED.
  • The initial query status is usually PENDING or RUNNING.
  • When the status changes to SUCCEEDED, the response contains the generated video URL.
  • If the status is FAILED, check the error message and retry the task.
  • If the status is CANCELED, the task has been canceled. To continue, resubmit the task.
  • If the status is UNKNOWN, the task does not exist or its status is unknown. This may occur when the task_id does not exist or the 24-hour validity period has expired.

submit_time string

The time when the task was submitted. The format is YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

The time when the task was executed. The format is YYYY-MM-DD HH:mm:ss.SSS.

end_time string

The time when the task was completed. The format is YYYY-MM-DD HH:mm:ss.SSS.

video_urlstring

The video URL. Returned only when task_status is SUCCEEDED.

Valid for 24 hours. You can download the video from this URL. The video is in MP4 format (H.264 encoding).

orig_prompt string

The original input prompt, corresponding to the request parameter prompt.

actual_prompt string

The optimized prompt used when prompt rewriting is enabled. Not returned when disabled.

codestring

Error code. Returned only for failed requests. See Error codes.

messagestring

Detailed error message. Returned only for failed requests. See Error codes.

usage object

Task usage statistics. Only successful results are counted.

Properties

video_duration integer

The duration of the generated video in seconds, which is always 5. Billing formula: Cost = Video seconds × Unit price.

video_count integer

The number of videos generated. This value is fixed at 1.

video_ratio string

Currently, this value is returned only by 2.1 models. The aspect ratio of the generated video, fixed as standard.

SR integer

Currently, this value is returned only by 2.2 models. The resolution tier of the generated video, with enumerated values 480, 720, and 1080.

request_idstring

Unique request identifier for tracing and troubleshooting.

Task succeeded

Video URLs are valid for only 24 hours and then automatically purged. Save generated videos promptly.

{
    "request_id": "ec016349-6b14-9ad6-8009-xxxxxx",
    "output": {
        "task_id": "3f21a745-9f4b-4588-b643-xxxxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2025-04-18 10:36:58.394",
        "scheduled_time": "2025-04-18 10:37:13.802",
        "end_time": "2025-04-18 10:45:23.004",
        "video_url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.mp4?xxxxx",
        "orig_prompt": "写实风格,一只黑色小猫好奇地看向天空,镜头从平视逐渐上升,最后俯拍它的好奇的眼神。",
        "actual_prompt": "写实风格,一只黑色小猫好奇地看向天空,镜头从平视逐渐上升,最后俯拍它的好奇的眼神。小猫的黄色眼睛明亮有神,毛发光滑,胡须清晰可见。背景是简单的浅色墙面,突显小猫的黑色身影。近景特写,强调小猫的表情变化和眼神细节。"
    },
    "usage": {
        "video_duration": 5,
        "video_count": 1,
        "SR": 480
    }
}

Task failed

If the task execution fails, task_status will be set to FAILED, and an error code and message will be provided. See Error codes for troubleshooting.

{
    "request_id": "e5d70b02-ebd3-98ce-9fe8-759d7d7b107d",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-a0c6a421c010",
        "task_status": "FAILED",
        "code": "InvalidParameter",
        "message": "The size is not match xxxxxx"
    }
}

Task query expired

The task_id can be used for queries for 24 hours. After it expires, the query will no longer be available, and the following error message will be returned.

{
    "request_id": "a4de7c32-7057-9f82-8581-xxxxxx",
    "output": {
        "task_id": "502a00b1-19d9-4839-a82f-xxxxxx",
        "task_status": "UNKNOWN"
    }
}

DashScope SDK calls

The SDK's parameter names are largely consistent with the HTTP API, and the parameter structure follows the conventions of each programming language.

Because image-to-video tasks are long-running (typically 1–5 minutes), the SDK handles the asynchronous HTTP calls internally, supporting both synchronous and asynchronous call methods.

The actual processing time depends on the number of tasks in the queue and service performance. Please be patient.

Python SDK calls

ImportantBefore you run the following code, ensure your DashScope Python SDK version is at least2.0.1.

Older versions may trigger errors such as "url error, please check url!". See Install SDK to update.

Set the region based on the model's region (passed in when constructing the Client; the region value varies by region):

China (Beijing)

region="cn-beijing"

Replace {WorkspaceId} with your actual workspace ID.

Singapore

region="ap-southeast-1"

Replace {WorkspaceId} with your actual workspace ID.

Sample code

Synchronous call

This example demonstrates three image input methods: public URL, Base64 encoding, and local file path.

Request example
import base64
import os
import mimetypes
import dashscope
from dashscope import DashScopeError

# 以下为华北2(北京)地域的配置。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    # 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

# --- 辅助函数:用于 Base64 编码 ---
# 格式为 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("不支持或无法识别的图像格式")
    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}"

"""
图像输入方式说明:
以下提供了三种图片输入方式,三选一即可

1. 使用公网URL - 适合已有公开可访问的图片
2. 使用本地文件 - 适合本地开发测试
3. 使用Base64编码 - 适合私有图片或需要加密传输的场景
"""

# 【方式一】使用公网图片 URL
first_frame_url = "https://wanx.alicdn.com/material/20250318/first_frame.png"
last_frame_url = "https://wanx.alicdn.com/material/20250318/last_frame.png"

# 【方式二】使用本地文件(支持绝对路径和相对路径)
# 格式要求:file:// + 文件路径
# 示例(绝对路径):
# first_frame_url = "file://" + "/path/to/your/first_frame.png"  # Linux/macOS
# last_frame_url = "file://" + "C:/path/to/your/last_frame.png"  # Windows
# 示例(相对路径):
# first_frame_url = "file://" + "./first_frame.png"              # 以实际路径为准
# last_frame_url = "file://" + "./last_frame.png"                # 以实际路径为准

# 【方式三】使用Base64编码的图片
# first_frame_url = encode_file("./first_frame.png")            # 以实际路径为准
# last_frame_url = encode_file("./last_frame.png")              # 以实际路径为准

def sample_sync_call_kf2v():
    print('please wait...')
    # generate 为一步式调用(提交任务并等待完成),返回已完成的 Job
    # first_frame_url / last_frame_url 为 input 段字段,不在具名签名内,经 extra_input 透传
    try:
        job = client.videos.generate(model="wan2.2-kf2v-flash",
                                     prompt="写实风格,一只黑色小猫好奇地看向天空,镜头从平视逐渐上升,最后俯拍它的好奇的眼神。",
                                     extra_input={'first_frame_url': first_frame_url,
                                                  'last_frame_url': last_frame_url},
                                     resolution="720P",
                                     prompt_extend=True)
        print(job)
        print(job.video_url)
    except DashScopeError as e:
        print(f"HTTP返回码:{e.status_code}")
        print(f"错误码:{e.code}")
        print(f"错误信息:{e.message}")
        print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

if __name__ == '__main__':
    sample_sync_call_kf2v()
Response example

The video_url is valid for 24 hours. Please download the video promptly.

{
    "request_id": "efa545b3-f95c-9e3a-a3b6-xxxxxx",
    "task_id": "721164c6-8619-4a35-a6d9-xxxxxx",
    "status": "SUCCEEDED",
    "video_url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.mp4?xxxxx",
    "task_metrics": {
        "TOTAL": 1,
        "SUCCEEDED": 1,
        "FAILED": 0
    },
    "usage": {
        "video_count": 1,
        "video_duration": 5,
        "video_ratio": "standard"
    }
}

Asynchronous call

This example demonstrates an asynchronous call, which returns the task ID immediately; use fetch to check the task status, or call wait to block until the task completes (with automatic polling).

Request example
import os
import dashscope
from dashscope import DashScopeError

# 以下为华北2(北京)地域的配置,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

Java SDK calls

ImportantBefore you run the following code, ensure your DashScope Java SDK version is at least2.20.9.

Older versions may trigger errors such as "url error, please check url!". See Install SDK to update.

Sample code

Synchronous call

This example demonstrates a synchronous call and supports three image input methods: public URL, Base64 encoding, and local file path.

Request example
// 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.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.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 环境要求
 *      dashscope java SDK >= 2.20.9
 * 更新maven依赖:
 *      https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
 */
public class Kf2vSync {

    static {
        // 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。

Asynchronous call

This example demonstrates an asynchronous call, which immediately returns a task ID. You must then poll for the task status or wait for the task to complete.

Request example
// 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;

/**
 * 环境要求
 *      dashscope java SDK >= 2.20.9
 * 更新maven依赖:
 *      https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
 */

public class Kf2vAsync {

    static {
        // 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。

Limitations

  • Data retention: The task task_id and video video_url are retained for 24 hours, after which they cannot be queried or downloaded.
  • Audio support: The service generates silent videos only. To generate audio, use speech synthesis.
  • Content Moderation: Content Moderation reviews all input prompts, images, and output videos. If any content violates the usage policies, the service returns an "IPInfringementSuspect" or "DataInspectionFailed" error. For details, see Error codes.

Error codes

If a model call fails, see Error codes for troubleshooting.

FAQ

Q: How to generate a specific aspect ratio?

A: The output video's aspect ratio depends on the first frame image (first_frame_url). However, an exact ratio (such as a strict 3:4) cannot be guaranteed, and may deviate slightly.

  • Why does the aspect ratio deviate?

    The model uses the aspect ratio of the input image as the baseline and, combined with the total pixels of the configured resolution tier (resolution), automatically calculates the closest valid resolution. Because the video's length and width must be multiples of 16, the model makes minor adjustments to the final resolution. Therefore, the output ratio cannot be guaranteed to be exactly 3:4, but it will be very close.

    • For example: with an input image of 750×1000 (aspect ratio 3:4 = 0.75) and resolution set to "720P" (target total pixels approximately 920,000), the actual output is 816×1104 (aspect ratio ≈ 0.739, total pixels approximately 900,000).
  • Best practices:

    • Input Image: For best results, use a first frame image that matches your target aspect ratio.
    • Post-processing: If a strict aspect ratio is required, use a video editing tool to crop the generated video or add black bars.

Q: How do I get the domain name whitelist for video storage?

A: Videos generated by models are stored in OSS. The API returns a temporary public URL. To configure a firewall whitelist for this download URL, note the following: The underlying storage may change dynamically based on business conditions. This topic does not provide a fixed OSS domain name whitelist to prevent access issues caused by outdated information. If you have security control requirements, contact your account manager to obtain the latest OSS domain name list.