Skip to main content

Image-to-video: first and last frames

The Wan image-to-video model generates smooth videos from a first-frame image, a last-frame image, and an optional text prompt.

  • Core capabilities: Fixed 5-second duration, custom resolution (480P/720P/1080P), prompt rewriting, and watermarking.
  • Video effect templates: Upload only the first-frame image and select an effect template to generate a video with a specific dynamic effect.
Quick links:API reference|Prompt guide| Wanx I2V video effects list

Getting started

PromptFirst frameLast frameOutput video
A cute blue monster with a slightly sad expression stands in the rain. The camera slowly zooms in and stops on the moment it looks up at the sky.
image
image
Before making calls, first obtain and configure an API Key, and then configure the API Key in environment variables. To make calls through the SDK, please install the DashScope SDK.
  • Python SDK
  • Java SDK
  • curl
Please ensure that the DashScope Python SDK version is no lower than 2.0.1 before running the following code.If the version is too old, errors such as "url error, please check url!" may occur. Refer to Install SDK to update.
import os
import dashscope
from dashscope import DashScopeError

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

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': "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260126/ixdxvt/wan-kf2v-blue-1.png",
                                              'last_frame_url': "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260126/nhtdrc/wan-kf2v-blue-2.png"},
                                 duration=5,  # 固定为5,不可修改
                                 resolution="720P",
                                 prompt_extend=True,
                                 watermark=True)
    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")
Sample Output (HTTP API response)
The video_url is valid for 24 hours. Download the video in time.
{
    "request_id": "c1209113-8437-424f-a386-xxxxxx",
    "output": {
        "task_id": "966cebcd-dedc-4962-af88-xxxxxx",
        "task_status": "SUCCEEDED",
        "video_url": "https://dashscope-result-sh.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx",
         ...
    },
    ...
}

Applicable scope

  • Models supported vary by region, and resources are independent of each other. For the models supported in each region, see the Model Studio console.
  • When making calls, ensure that the model, Endpoint URL, and API Key all belong to the same region; cross-region calls will fail.
The sample code in this document applies to the Beijing region.

Core capabilities

First and last frame to video

Supported models: All models. Feature description: Generates a video (without sound) with a smooth transition based on the first frame and the last frame. Parameter settings:
  • first_frame_url: Required. You must provide the first frame image.
  • last_frame_url: Required. You must provide the last frame image.
  • prompt: Optional, but recommended. It controls the changes in the video.
PromptFirst frameLast frameOutput video
Realistic style, a small black cat curiously looking up at the sky, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down angle.
首帧图像
尾帧图像
  • Python SDK
  • Java SDK
  • curl
Ensure that the DashScope Python SDK version is 2.0.1 or later. For updates, refer to Install SDK.
import os
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",
)

def sample_async_call_kf2v():
    # 异步调用,返回一个task_id
    # first_frame_url / last_frame_url 为 input 段字段,不在具名签名内,经 extra_input 透传
    try:
        job = client.videos.jobs.create(model="wan2.2-kf2v-flash",
                                        prompt="写实风格,一只黑色小猫好奇地看向天空,镜头从平视逐渐上升,最后俯拍它的好奇的眼神。",
                                        extra_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"},
                                        duration=5,  # 固定为5,不可修改
                                        prompt_extend=True,
                                        watermark=True)
        print(job)
        print("task_id: %s" % job.task_id)
    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")
        return

    # 等待异步任务结束(指数退避轮询,默认总预算24小时)
    try:
        done = client.videos.jobs.wait(job)
        print(done)
        print(done.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_async_call_kf2v()

Use video effects

Supported models: wanx2.1-kf2v-plus. Feature description: You only need to provide the first frame, without a prompt or last frame image, and directly use the built-in effect template to apply a specific effect. Parameter settings:
  • template: Required. Specifies the effect name (for example, "mech1" for the Mechanical Awakening effect). Before making calls, see the Wanx I2V video effects list to confirm whether the model supports the effect; otherwise, the call may fail.
  • first_frame_url: Required. You must provide the first frame image.
  • last_frame_url: Ignored. When using effects, the last_frame_url field is invalid; leave it empty or do not pass it.
  • prompt: Ignored. When using effects, the prompt field is invalid; leave it empty or do not pass it.
First frameOutput video (effect video)
首尾帧生视频-视频特效-demo
  • Python SDK
  • Java SDK
  • curl
Ensure that the DashScope Python SDK version is 2.0.1 or later. For updates, refer to Install SDK.
import os
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",
)

def sample_async_call_kf2v():
    # 异步调用,返回一个task_id
    # first_frame_url / template(视频特效模板)为 input 段字段,不在具名签名内,经 extra_input 透传
    try:
        job = client.videos.jobs.create(model="wanx2.1-kf2v-plus",
                                        extra_input={'first_frame_url': "https://ty-yuanfang.oss-cn-hangzhou.aliyuncs.com/lizhengjia.lzj/tmp/11.png",
                                                     'template': "mech1"},
                                        resolution="720P",
                                        watermark=True)
        print(job)
        print("task_id: %s" % job.task_id)
    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")
        return

    # 等待异步任务结束(指数退避轮询,默认总预算24小时)
    try:
        done = client.videos.jobs.wait(job)
        print(done)
        print(done.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_async_call_kf2v()

How to input images

  • Number of images: One first frame image and one last frame image.
  • Input methods: Image URL, local file path, or Base64-encoded string.

Method 1: Image URL (HTTP API, SDK) Recommended

The file path requirements vary slightly across programming languages (Python/Java). Follow the rules below strictly when writing paths.Python SDK: supports both absolute and relative paths. File path rules:

Operating system

File path to pass in

Example (absolute path)

Example (relative path)

Linux / macOS

file:/{absolute or relative path of the file}

file:///home/images/test.png

file://./images/test.png

Windows

file://D:/images/test.png

file://./images/test.png

Java SDK: supports only absolute paths. File path rules:

Operating system

File path to pass in

Example (absolute path)

Linux / macOS

file:/{absolute path of the file}

file:///home/images/test.png

Windows

file://{absolute path of the file}

file:///D:/images/test.png

  • Example value: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDg...... (truncated for demonstration only).
  • Format requirements: Follow the data:{MIME_type};base64,{base64_data} format, where:
    • {base64_data}: the string obtained by Base64-encoding the image file.
    • {MIME_type}: the media type of the image, which must correspond to the file format.

      Image format

      MIME Type

      JPEG

      image/jpeg

      JPG

      image/jpeg

      PNG

      image/png

      BMP

      image/bmp

      WEBP

      image/webp

Sample code: multiple ways to input images

Python SDK
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()

Output video

  • Video count: 1.
  • Video specifications: Output specifications vary by model. For details, see Video specifications.
  • Video URL validity: 24 hours.
  • Video dimensions: determined by the input first frame image and the set resolution.
    • The model tries to keep the aspect ratio of the input first frame image unchanged while scaling the total pixel count close to the target. Due to encoding specifications, the width and height of the output video must be divisible by 16, and the model automatically fine-tunes the dimensions.
    • For example: input image 750×1000 (aspect ratio 3:4 = 0.75), with resolution set to "720P" (target total pixels ≈ 0.92 million). The final output may be 816 × 1104 (aspect ratio ≈ 0.739, total pixels ≈ 0.9 million), with both width and height being multiples of 16.

Billing and rate limits

  • For model free quotas and billing unit prices, see Model prices.
  • For model rate limits, see Wan series.
  • Billing details:
    • Input is not billed; output is billed. Output is billed by the number of video seconds successfully generated.
    • Failed model calls or processing errors incur no charges and do not consume the new user free quota.
    • I2V also supports savings plans.

API reference

I2V based on first and last frames API reference

FAQ

Q: How do I generate a video with a specific aspect ratio (such as 3:4)?

A: The current API does not support directly specifying the video aspect ratio. You can only set the video resolution with the resolution parameter. resolution controls the total number of pixels in the video, not a strictly fixed aspect ratio. The model prioritizes preserving the original aspect ratio of the first frame image (first_frame_url) and fine-tunes it on that basis to meet video encoding requirements (that is, both width and height must be multiples of 16). Therefore, if you want an output close to 3:4, we recommend uploading a first frame image with an aspect ratio of 3:4, and the model will keep that ratio as much as possible.
For example: input image 750×1000 (aspect ratio 3:4 = 0.75), with resolution set to "720P" (target total pixels ≈ 0.92 million). The final output may be 816 × 1104 (aspect ratio ≈ 0.739, total pixels ≈ 0.9 million), with both width and height being multiples of 16.

Q: Why does the “url error, please check url!” error occur when running SDK code?

Example: 750×1000 input (3:4) with resolution="720P" (target ≈920K pixels) may output 816×1104 (≈0.739 ratio, ≈900K pixels, both divisible by 16).
  • The DashScope Python SDK version must be 2.0.1 or later.
  • The DashScope Java SDK version must be 2.22.6 or later.
If the SDK version is too old, the “url error, please check url!” error may occur. Refer to Upgrade SDK to update.