Skip to main content

Wan - image-to-video - first frame API reference (2.1-2.6)

The Wan image-to-video model generates a smooth video from a first-frame image and a text prompt .

Related documents: User guide
Wan 2.7 - image-to-video supports first-frame-to-video, first-and-last-frame-to-video, and video continuation. We recommend this version.The image-to-video (based on first frame) feature for Wan 2.6 and earlier models supports only first-frame-to-video.

Availability

Your model, endpoint URL, and API key must be in the same region. Cross-region calls fail.
The sample code in this topic is for the China (Beijing) region.
Alibaba 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

Image-to-video tasks use asynchronous invocation (typically 1–5 minutes): create task -> poll for results.

Step 1: Create a task

  • Beijing
  • Singapore
  • Virginia
  • Frankfurt
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis
Replace {WorkspaceId} with your actual workspace ID.
  • After the task is created, use the task_id returned by the API to query the result. task_id is valid for 24 hours. Do not create tasks repeatedly; polling is sufficient to obtain the result.
  • For beginner guidance, see Postman.

Request parameters

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)Asynchronous processing configuration parameter. HTTP requests support asynchronous mode only, and it must be set to enable.
If this request header is missing, the error "current user api does not support synchronous calls" is returned.
Request body
model string (Required)The model name. Available models and pricing: model pricing.Example: wan2.6-i2v-flash.input object (Required)Input fields including the prompt.

Properties

prompt string (Optional)Describes the desired visual elements and characteristics of the generated video.Supports Chinese and English. Each character counts as one. Text exceeding the limit is truncated. Length limits by model:
  • Wan2.6 and Wan2.5 series models: A maximum of 1,500 characters.
  • wan2.2 and wanx2.1 series models: A maximum of 800 characters.
When you use video effects (that is, template is not empty), the model ignores the prompt parameter and you do not need to set it.Example: A kitten running on the grass.Prompt writing tips: Text-to-Video/Image-to-Video Prompt Guide.negative_prompt string (Optional)Describes what to exclude from the video, constraining the output.Supports Chinese and English. Maximum 500 characters; longer text is truncated.Example: low resolution, errors, worst quality, low quality, disfigured, extra fingers, poor proportions, etc.img_url string (Required)The URL or Base64-encoded data of the initial image.Image constraints:
  • Image format: JPEG, JPG, PNG (alpha channel not supported), BMP, or WEBP.
  • Image resolution: Both width and height must be within [240, 8000] pixels.
  • File size:
    • Wan2.6 and Wan2.5 series models: A maximum of 20 MB.
    • wan2.2 and wanx2.1 series models: A maximum of 10 MB.
Supported input formats:
  1. Public URL:
  2. Temporary URL:
  3. Base64-encoded image string:
    • Data format: data:{MIME_type};base64,{base64_data}.
    • Example: data:image/png;base64,GDU7MtCZzEbTbmRZ...... (truncated for brevity).
    • For details, see Input Image.
audio_url string (Optional)Supported models: Wan2.6 and Wan2.5 series models.The URL of the audio file. The model generates the video using this audio.Supported input formats:
  1. Public URL:
  2. Temporary URL:
    • Supports the OSS protocol. You must obtain the URL by calling the Upload File to Get Temporary URL operation.
    • Example: oss://dashscope-instant/xxx/2024-07-18/xxx/xxx.mp3.
Audio constraints:
  • Format: WAV, MP3.
  • Duration: 3–30s.
  • File size: A maximum of 15 MB.
  • Out-of-range handling: If the audio duration exceeds the specified duration (5 or 10 seconds), the system automatically truncates the audio to the first 5 or 10 seconds, and the rest is discarded. If the audio is shorter than the video duration, the video is silent after the audio ends. For example, if the audio is 3 seconds long and the video duration is 5 seconds, the first 3 seconds of the output video will have sound, and the last 2 seconds will be silent.
Example: https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/ozwpvi/rap.mp3.template string (Optional)The name of the video effect template. If you leave this empty, no video effect is applied.Supported templates vary by model. Check the Wan - Image-to-Video - Video Effects List before calling.Example: flying, which enables the "Magic Levitation" video effect.
parameters object (Optional)Controls for resolution, duration, intelligent prompt rewriting, and watermarks.

Properties

resolution string (Optional)
Resolution directly affects cost. Before you call the API, confirm the model pricing.
Specifies the video resolution tier for generation, which adjusts the video clarity (total pixels). Based on the selected resolution tier, the model automatically scales to a similar total pixel count. The video aspect ratio will keep consistent with the aspect ratio of the input image img_url as much as possible. For more information, see FAQ.The default value and available enumeration values of this parameter depend on the model parameter, as follows:
  • wan2.6-i2v-flash: Valid values: 720P, 1080P. Default value: 1080P.
  • wan2.6-i2v: Valid values: 720P, 1080P. Default value: 1080P.
  • wan2.5-i2v-preview: Valid values: 480P, 720P, 1080P. Default value: 1080P.
  • wan2.2-i2v-flash: Valid values: 480P, 720P, 1080P. Default value: 720P.
  • wan2.2-i2v-plus: Valid values: 480P, 1080P. Default value: 1080P.
  • wanx2.1-i2v-turbo: Valid values: 480P, 720P. Default value: 720P.
  • wanx2.1-i2v-plus: Valid values: 720P. Default value: 720P.
Example: 1080P.duration integer (Optional)
Duration directly affects cost. Before you call the API, confirm the model pricing.
The duration of the generated video, in seconds. The value of this parameter depends on the model parameter:
  • wan2.6-i2v-flash: An integer in [2, 15]. Default: 5.
  • wan2.6-i2v: An integer in [2, 15]. Default: 5.
  • wan2.5-i2v-preview: Valid values: 5, 10. Default: 5.
  • wan2.2-i2v-plus: Fixed at 5 seconds and cannot be modified.
  • wan2.2-i2v-flash: Fixed at 5 seconds and cannot be modified.
  • wanx2.1-i2v-plus: Fixed at 5 seconds and cannot be modified.
  • wanx2.1-i2v-turbo: Valid values: 3, 4, or 5. Default: 5.
Example: 5.prompt_extend boolean (Optional)Whether to enable prompt rewriting. When enabled, an LLM rewrites the input prompt. This improves generation quality for shorter prompts but increases processing time.
  • true (default)
  • false
Example: true.shot_type string (Optional)Supported models: Wan2.6 series models.Specifies the shot type of the generated video: a single continuous shot or a sequence of multiple shots.This parameter takes effect only when "prompt_extend": true.Parameter priority: shot_type > prompt. For example, if shot_type is set to "single", even if the prompt contains "generate a multi-shot video", the model will still output a single-shot video.Valid values:
  • single: Default value. Generates a single-shot video.
  • multi: Generates a multi-shot video.
Example: single.
Use this parameter when you need strict control over the narrative structure, such as a single shot for product demos or multiple shots for short films.
audio boolean (Optional)
This affects cost. Videos with sound and silent videos have different prices. Check pricing in the Model Studio console.
Supported model: wan2.6-i2v-flash.Specifies whether to generate a video with sound.Parameter priority: audio > audio_url. When audio=false, the output is still a silent video even if an audio_url is provided, and billing is based on a silent video.Valid values:
  • true: Default value. Generates a video with sound.
  • false: Generates a silent video.
Example: true.watermark boolean (Optional)Specifies whether to add an "AI Generated" watermark in the lower-right corner of the video.
  • false: Default value. No watermark is added.
  • true: Adds a watermark.
Example: false.seedinteger(Optional)The random number seed. Value range: [0, 2147483647].If not specified, the system generates one. For better reproducibility, use a fixed seed.Generation is probabilistic. Even with the same seed, results may differ.Example: 12345.
  • Multi-shot narrative
  • Automatic dubbing
  • Custom audio
  • Silent video
  • Base64
  • Video effects
  • Negative prompt
This feature is supported only by the Wan2.6 series models.You can enable it by setting "prompt_extend": true and "shot_type":"multi".
# 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。

curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wan2.6-i2v-flash",
    "input": {
        "prompt": "一幅都市奇幻艺术的场景。一个充满动感的涂鸦艺术角色。一个由喷漆所画成的少年,正从一面混凝土墙上活过来。他一边用极快的语速演唱一首英文rap,一边摆着一个经典的、充满活力的说唱歌手姿势。场景设定在夜晚一个充满都市感的铁路桥下。灯光来自一盏孤零零的街灯,营造出电影般的氛围,充满高能量和惊人的细节。视频的音频部分完全由他的rap构成,没有其他对话或杂音。",
        "img_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png",
        "audio_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/ozwpvi/rap.mp3"
    },
    "parameters": {
        "resolution": "720P",
        "prompt_extend": true,
        "duration": 10,
        "shot_type":"multi"
    }
}'

Response parameters

output objectInformation about the task output.

Properties

task_id stringThe task ID. Valid for queries for 24 hours.task_status stringThe status of the task.

Enumeration values

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: The task does not exist or its status is unknown.
request_idstringUnique request identifier for tracing and troubleshooting.codestringError code. Returned only for failed requests. See Error codes.messagestringDetailed error message. Returned only for failed requests. See Error codes.
  • Successful response
  • Error 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"
}

Step 2: Query the task result

  • Beijing
  • Singapore
  • Virginia
  • Frankfurt
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
Replace {WorkspaceId} with your actual workspace ID.
  • Polling recommendation: Video generation takes several minutes. We recommend using a polling mechanism and setting a reasonable query interval (such as 15 seconds) to obtain the result.
  • Task status transitions: PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
  • Result link: The video link is returned after the task succeeds, with a validity of 24 hours. We recommend downloading the video 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 returns a task status of 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

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
Replace {task_id} with the task_id value returned by the previous API call. The task_id is valid for queries for 24 hours, Replace {WorkspaceId} with your actual workspace ID.
curl -X GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

Response parameters

outputobjectInformation about the task output.

Properties

task_id stringThe task ID. Valid for queries for 24 hours.task_status stringThe status of the task.

Enumeration values

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • 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, submit the task again.
  • 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 stringThe time when the task was submitted. format is YYYY-MM-DD HH:mm:ss.SSS.scheduled_time stringThe time when the task was executed. format is YYYY-MM-DD HH:mm:ss.SSS.end_time stringThe time when the task was completed. format is YYYY-MM-DD HH:mm:ss.SSS.video_urlstringVideo URL. Returned only when task_status is SUCCEEDED.Valid for 24 hours. The video is in MP4 format with H.264 encoding.orig_prompt stringThe original input prompt, corresponding to the request parameter prompt.actual_prompt stringWhen prompt_extend=true, the system intelligently rewrites the input prompt, and this field returns the optimized prompt actually used for generation.
  • If prompt_extend=false, this field is not returned.
  • Note: The wan2.6 model does not return this field, regardless of the value of prompt_extend.
codestringError code. Returned only for failed requests. See Error codes.messagestringDetailed error message. Returned only for failed requests. See Error codes.
usage objectUsage statistics for the task, which are counted only for successful tasks.

Properties

Parameters returned by wan2.6 series models

input_video_duration integerThe duration of the input video in seconds. This is always 0, as video input is not currently supported.output_video_duration integerReturned only when using wan2.6 models.The duration of the output video in seconds. This value matches the input.duration.duration integerThe total video duration, used for billing.Billing formula: duration=input_video_duration+output_video_duration.SR integerReturned only when using wan2.6 models. The resolution tier of the generated video. Example: 720.video_count integerThe number of generated videos. This is fixed at 1.audiobooleanReturned only when using the wan2.6-i2v-flash model. Indicates whether the output is a video with audio.
duration integerThe duration of the generated video in seconds. Possible values: 5, 10.Billing formula: Cost = Video duration in seconds × Unit price.SR integerThe resolution of the generated video. Possible values: 480, 720, 1080.video_count integerThe number of generated videos. This is fixed at 1.
video_duration integerThe duration of the generated video in seconds. Possible values: 3, 4, 5.Billing formula: Cost = Video duration in seconds × Unit price.video_ratio stringThe aspect ratio of the generated video. This value is always "standard".video_count integerThe number of generated videos. This is fixed at 1.
request_idstringUnique request identifier for tracing and troubleshooting.
  • Task succeeded
  • Task failed
  • Task query expired
Video URLs are valid for only 24 hours and then automatically purged. Save generated videos promptly.
{
    "request_id": "2ca1c497-f9e0-449d-9a3f-xxxxxx",
    "output": {
        "task_id": "af6efbc0-4bef-4194-8246-xxxxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2025-09-25 11:07:28.590",
        "scheduled_time": "2025-09-25 11:07:35.349",
        "end_time": "2025-09-25 11:17:11.650",
        "orig_prompt": "一幅都市奇幻艺术的场景。一个充满动感的涂鸦艺术角色。一个由喷漆所画成的少年,正从一面混凝土墙上活过来。他一边用极快的语速演唱一首英文rap,一边摆着一个经典的、充满活力的说唱歌手姿势。场景设定在夜晚一个充满都市感的铁路桥下。灯光来自一盏孤零零的街灯,营造出电影般的氛围,充满高能量和惊人的细节。视频的音频部分完全由他的rap构成,没有其他对话或杂音。",
        "video_url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.mp4?Expires=xxx"
    },
    "usage": {
        "duration": 10,
        "input_video_duration": 0,
        "output_video_duration": 10,
        "video_count": 1,
        "SR": 720
    }
}

DashScope SDK calls

SDK parameter names are largely consistent with the HTTP API, following each language's conventions. Image-to-video tasks typically take 1–5 minutes. The SDK wraps the asynchronous HTTP call process and supports both synchronous and asynchronous calls.
Processing time depends on the task queue and service status.

Python SDK

Make sure your DashScope Python SDK version is at least2.0.1 before running the following code.Older versions might trigger errors such as "url error, please check url!". To update, refer to Install the SDK.
Set the region according to the model's region (passed in when constructing the Client; the region value varies by region):
  • Beijing
  • Singapore
  • Virginia
  • Frankfurt
region="cn-beijing"
Replace {WorkspaceId} with your actual workspace ID.

Sample code

  • Synchronous call
  • Asynchronous call
A synchronous call blocks until video generation completes. 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: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
# 示例:使用一个公开的图片URL
img_url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png"

# 【方式二】使用本地文件(支持绝对路径和相对路径)
# 格式要求:file:// + 文件路径
# 示例(绝对路径):
# img_url = "file://" + "/path/to/your/img.png"    # Linux/macOS
# img_url = "file://" + "/C:/path/to/your/img.png"  # Windows
# 示例(相对路径):
# img_url = "file://" + "./img.png"                # 相对当前执行文件的路径

# 【方式三】使用Base64编码的图片
# img_url = encode_file("./img.png")

# 设置音频audio url
audio_url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/ozwpvi/rap.mp3"

def sample_call_i2v():
    # generate 为一步式调用(提交任务并等待完成),返回已完成的 Job
    print('please wait...')
    # audio_url / negative_prompt 为 input 段字段,不在具名签名内,经 extra_input 透传
    try:
        job = client.videos.generate(model='wan2.6-i2v-flash',
                                     prompt='一幅都市奇幻艺术的场景。一个充满动感的涂鸦艺术角色。一个由喷漆所画成的少年,正从一面混凝土墙上活过来。他一边用极快的语速演唱一首英文rap,一边摆着一个经典的、充满活力的说唱歌手姿势。场景设定在夜晚一个充满都市感的铁路桥下。灯光来自一盏孤零零的街灯,营造出电影般的氛围,充满高能量和惊人的细节。视频的音频部分完全由他的rap构成,没有其他对话或杂音。',
                                     image_url=img_url,
                                     extra_input={'audio_url': audio_url,
                                                  'negative_prompt': ""},
                                     resolution="720P",
                                     duration=10,
                                     prompt_extend=True,
                                     watermark=False,
                                     seed=12345)
        print(job)
        print("video_url:", 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_call_i2v()
Response example
The video_url is valid for 24 hours. Download the video before it expires.
{
    "request_id": "2794c7a3-fe8c-4dd4-a1b7-xxxxxx",
    "task_id": "c15d5b14-07c4-4af5-b862-xxxxxx",
    "status": "SUCCEEDED",
    "video_url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxx.mp4?Expires=xxx",
    "task_metrics": {
        "TOTAL": 1,
        "SUCCEEDED": 1,
        "FAILED": 0
    },
    "usage": {
        "video_count": 1,
        "duration": 10,
        "input_video_duration": 0,
        "output_video_duration": 10,
        "audio": true,
        "SR": 720
    }
}

Java SDK

Make sure your DashScope Java SDK version is at least2.22.6 before running the following code.Older versions might trigger errors such as "url error, please check url!". To update, refer to Install the SDK.
Set the baseHttpApiUrl according to the model's region:
  • Beijing
  • Singapore
  • Virginia
  • Frankfurt
Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
Replace {WorkspaceId} with your actual workspace ID.

Sample code

  • Synchronous call
  • Asynchronous call
A synchronous call blocks until video generation completes. This example demonstrates 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.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 {
        // 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
        // 获取URL:https://help.aliyun.com/zh/model-studio/image-to-video-api-reference
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
    }

    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
    // 获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    /**
     * 图像输入方式说明:三选一即可
     *
     * 1. 使用公网URL - 适合已有公开可访问的图片
     * 2. 使用本地文件 - 适合本地开发测试
     * 3. 使用Base64编码 - 适合私有图片或需要加密传输的场景
     */

    //【方式一】公网URL
    static String imgUrl = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png";

    //【方式二】本地文件路径(file://+绝对路径)
    // static String imgUrl = "file://" + "/your/path/to/img.png";    // Linux/macOS
    // static String imgUrl = "file://" + "/C:/your/path/to/img.png";  // Windows

    //【方式三】Base64编码
    // static String imgUrl = Image2Video.encodeFile("/your/path/to/img.png");

    // 设置音频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 {
        // 设置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("一幅都市奇幻艺术的场景。一个充满动感的涂鸦艺术角色。一个由喷漆所画成的少年,正从一面混凝土墙上活过来。他一边用极快的语速演唱一首英文rap,一边摆着一个经典的、充满活力的说唱歌手姿势。场景设定在夜晚一个充满都市感的铁路桥下。灯光来自一盏孤零零的街灯,营造出电影般的氛围,充满高能量和惊人的细节。视频的音频部分完全由他的rap构成,没有其他对话或杂音。")
                        .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));
    }

     /**
     * 将文件编码为Base64字符串
     * @param filePath 文件路径
     * @return Base64字符串,格式为 data:{MIME_type};base64,{base64_data}
     */
    public static String encodeFile(String filePath) {
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            throw new IllegalArgumentException("文件不存在: " + filePath);
        }
        // 检测MIME类型
        String mimeType = null;
        try {
            mimeType = Files.probeContentType(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("无法检测文件类型: " + filePath);
        }
        if (mimeType == null || !mimeType.startsWith("image/")) {
            throw new IllegalArgumentException("不支持或无法识别的图像格式");
        }
        // 读取文件内容并编码
        byte[] fileBytes = null;
        try{
            fileBytes = Files.readAllBytes(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("无法读取文件内容: " + 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);
    }
}
Response example
The video_url is valid for 24 hours. Download the video before it expires.
{
    "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": "一幅都市奇幻艺术的场景。一个充满动感的涂鸦艺术角色。一个由喷漆所画成的少年,正从一面混凝土墙上活过来。他一边用极快的语速演唱一首英文rap,一边摆着一个经典的、充满活力的说唱歌手姿势。场景设定在夜晚一个充满都市感的铁路桥下。灯光来自一盏孤零零的街灯,营造出电影般的氛围,充满高能量和惊人的细节。视频的音频部分完全由他的rap构成,没有其他对话或杂音。",
        "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": ""
}

Limitations

  • Data retention: Both the task task_id and the video url are retained for only 24 hours; after expiration, they can no longer be queried or downloaded.
  • Content moderation: The input content (such as prompts and images) and the output video are subject to content security review. If prohibited content is detected, the “IPInfringementSuspect” or “DataInspectionFailed” error is returned. For more information, see Error code.

Known limitations

When using wan2.6-i2v-flash to generate animations of continuously rotating circular objects (such as rings, gears, and dials), the video may briefly freeze (the frame stays still for about 1 second) after about 3 seconds. To generate such continuous rotation effects, we recommend switching to the Wan2.7-I2V model to avoid this issue.

Error codes

If a model call returns an error message, see Error codes.

FAQ

Q: How to generate a video with a specific aspect ratio?

A: The input first-frame image (img_url) determines the aspect ratio of the output video. However, an exact ratio like 3:4 is not guaranteed, as minor deviations may occur.
  • Why do deviations occur? 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 width and height of the video must be multiples of 16, the model fine-tunes the final resolution. Therefore, the output ratio cannot be guaranteed to be exactly 3:4, but it will be very close.
    • Example: The input image is 750×1000 (aspect ratio 3:4 = 0.75), and resolution = "720P" is set (target total pixels approximately 920,000). The actual output is 816×1104 (aspect ratio ≈ 0.739, total pixels approximately 900,000).
  • Best practice:
    • Control the input: For best results, use a first-frame image that already has your target aspect ratio.
    • Post-processing: If you need a strict aspect ratio, crop the video or add black bars using an editing tool after generation.

Q: How to get the video storage domain allowlist?

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. 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.