QwenCloudBRASIL
Tradução de apoio para consulta. Código e identificadores técnicos preservados. Consultar referência original ↗

Imagem para vídeo: primeira e última molduras.

Animar entre dois quadros

Tradução:wan2.7](/api-reference/video-generation/wan27-image-to-video/create-task), [wan2.2](/api-reference/video-generation/wan-image-to-video-first-last-frames/create-task(Guia de Prompt) (/developer-guides/accuracy-tuning/video-generation)

Começando.

<table style={{width: "100%", borderCollapse: "separate", borderSpacing: "8px 0", tableLayout: "fixed"}}> <tr> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}>Prompt</th> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}> Primeiro quadro</th> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}>Última moldura</th> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}>** Vídeo de saída **</th> </tr>

<tr> <td style={{verticalAlign: "top"}}> Um monstro azul bonito com uma expressão um pouco triste fica na chuva. A câmera lentamente se aproxima e pára no momento em que olha para o céu. </td>

<td style={{verticalAlign: "top"}}>
  [Imagem] (https://help-static-aliyun-doc.aliyuncs.com/assets/img/en-US/7108770771/p958738.png)
</td>

<td style={{verticalAlign: "top"}}>
  [Imagem] (https://help-static-aliyun-doc.aliyuncs.com/assets/img/en-US/7108770771/p1049069.png)
</td>

<td style={{verticalAlign: "top"}}>
  <video style={{display: "block", width: "100%"}} src="https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/en-US/20260126/hpzamh/wan-kf2v-demo.mp4" controls title="Image-to-video: first and last frames" />
</td>

</tr> </table>

Antes de chamar a API, [obtenha uma chave de API] (/api-reference/preparation/api-key). Então [defina sua chave API como uma variável de ambiente] (/api-reference/preparation/export-api-key-env).

curl (wan2.7)

Wan 2.7 usa o mesmo. `wan2.7-i2v`  Modelo como imagem de primeira imagem para vídeo. Forneça os dois. `first_frame` e `last_frame` na `media` Array.

 Passo 1: Criar uma tarefa

```bash
curl --location 'https://maas.qwencloudapi.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.7-i2v",
  "input": {
    "prompt": "Realistic style, a small black cat looks up at the sky curiously. The camera angle gradually rises from eye level, finally capturing its curious gaze from a top-down view.",
    "media": [
      {
        "type": "first_frame",
        "url": "https://wanx.alicdn.com/material/20250318/first_frame.png"
      },
      {
        "type": "last_frame",
        "url": "https://wanx.alicdn.com/material/20250318/last_frame.png"
      }
    ]
  },
  "parameters": {
    "resolution": "720P",
    "duration": 10,
    "prompt_extend": false,
    "watermark": true
  }
}'
```

 Passo 2: Obtenha o resultado usando a identificação da tarefa

 Substituir `{task_id}` com o `task_id` O valor retornado pela chamada anterior da API.

```bash
curl -X GET 'https://maas.qwencloudapi.com/api/v1/tasks/{task_id}' \
  -H "Authorization: Bearer $DASHSCOPE_API_KEY"
```



  ** Principais diferenças de wan2.2**: wan2.7  usa `resolution` (720P/1080P) em vez de dimensões de pixel, suporta 2-15s duração (não fixo em 5s), e usa o `media` Array em vez de `first_frame_url`/`last_frame_url`  Parâmetros. `watermark` predefinições para `false`.

curl (wan2.2)

 Passo 1: Crie uma tarefa para obter a identificação da tarefa

```bash
curl --location 'https://maas.qwencloudapi.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://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",
    "prompt": "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."
  },
  "parameters": {
    "resolution": "720P",
    "prompt_extend": true,
    "watermark": true
  }
}'
```

 Passo 2: Obtenha o resultado usando a identificação da tarefa

 Substituir `{task_id}` com o `task_id` O valor retornado pela chamada anterior da API.

```bash
curl -X GET https://maas.qwencloudapi.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
```

Python and Java SDK examples (wan2.2)

Para usar o SDK, [instale o DashScope SDK] (/api-reference/preparation/install-sdk).

Python SDK

     Certifique-se de que sua versão do DashScope Python SDK seja pelo menos`1.25.8`** antes de executar o código abaixo.

    Se sua versão é muito baixa, você pode ver erros como "erro de url, por favor, verifique url!"./api-reference/preparation/install-sdk).
  


  ```python
  import os
  from http import HTTPStatus
  from dashscope import VideoSynthesis
  import dashscope

  dashscope.base_http_api_url = 'https://maas.qwencloudapi.com/api/v1'
  api_key = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")

  print('please wait...')
  rsp = VideoSynthesis.call(api_key=api_key,
                              model="wan2.2-kf2v-flash",
                              prompt="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.",
                              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,  # Fixed at 5 seconds. Do not change.
                              prompt_extend=True,
                              watermark=True)
  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))
  ```

Java SDK

     Certifique-se de que sua versão do DashScope Java SDK seja pelo menos`2.22.6`** antes de executar o código abaixo.

    Se sua versão é muito baixa, você pode ver erros como "erro de url, por favor, verifique url!"./api-reference/preparation/install-sdk).
  


  ```java
  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;

  public class Image2Video {

    static {
      Constants.baseHttpApiUrl = "https://maas.qwencloudapi.com/api/v1";
    }

    // If you have not set an environment variable, replace the line below with: apiKey="sk-xxx"
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    public static void image2video() throws ApiException, NoApiKeyException, InputRequiredException {
      VideoSynthesis vs = new VideoSynthesis();
      VideoSynthesisParam param =
          VideoSynthesisParam.builder()
              .apiKey(apiKey)
              .model("wan2.2-kf2v-flash")
              .prompt("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.")
              .firstFrameUrl("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260126/ixdxvt/wan-kf2v-blue-1.png")
              .lastFrameUrl("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260126/nhtdrc/wan-kf2v-blue-2.png")
              .resolution("720P")
              .promptExtend(true)
              .watermark(true)
              .build();
      System.out.println("please wait...");
      VideoSynthesisResult result = vs.call(param);
      System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
      try {
        image2video();
      } catch (ApiException | NoApiKeyException | InputRequiredException e) {
        System.out.println(e.getMessage());
      }
      System.exit(0);
    }
  }
  ```

Sample output

video_url expira após 24 horas. Baixe o vídeo imediatamente.

{
  "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",
         ...
  },
  ...
}

Capacidades principais.

Descrição: Gera vídeos suaves de uma primeira estrutura e uma imagem de última estrutura.

wan2.7-i2v parâmetros

Use o media Array com first_frame e last_frame Tipos. O mesmo modelo e ponto final é usado tanto para a primeira e última geração de quadros.

wan2.2 / wan2.1 parâmetros

<table style={{width: "100%", borderCollapse: "separate", borderSpacing: "8px 0", tableLayout: "fixed"}}> <tr> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}>Prompt</th> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}> Primeiro quadro</th> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}>Última moldura</th> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}>** Vídeo de saída **</th> </tr>

<tr> <td style={{verticalAlign: "top"}}> Estilo realista. Um gatinho preto curioso olha para o céu. A câmera começa ao nível dos olhos e gradualmente sobe até capturar o olhar curioso do gatinho de cima. </td>

<td style={{verticalAlign: "top"}}>
  (Primeira imagem da moldura)https://help-static-aliyun-doc.aliyuncs.com/assets/img/en-US/1166661571/p944793.png)
</td>

<td style={{verticalAlign: "top"}}>
  (Última imagem do quadro)https://help-static-aliyun-doc.aliyuncs.com/assets/img/en-US/1166661571/p944794.png)
</td>

<td style={{verticalAlign: "top"}}>
  <video style={{display: "block", width: "100%"}} src="https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/en-US/20250704/qxiupv/24376238c6b4bc59486eeb7bb4012bfe3b329502da56ad7fc64e0b7a6746fd56.mp4" controls title="Image-to-video: first and last frames" />
</td>

</tr> </table>

Python SDK

   Certifique-se de que sua versão do DashScope Python SDK seja pelo menos `1.25.8`[Instalar o SDK] (/api-reference/preparation/install-sdk).



```python
import os
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope

dashscope.base_http_api_url = 'https://maas.qwencloudapi.com/api/v1'
api_key = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")

def sample_async_call_kf2v():
  # Asynchronous call returns a task_id
  rsp = VideoSynthesis.async_call(api_key=api_key,
                  model="wan2.2-kf2v-flash",
                  prompt="Realistic style. A curious black kitten looks up at the sky. The camera starts at eye level and gradually rises until it captures the kitten's curious gaze from above.",
                  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,  # Fixed at 5 seconds. Do not change.
                  prompt_extend=True,
                  watermark=True)
  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))

  # Wait for 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_kf2v()
```

Java SDK

   Certifique-se de que sua versão do DashScope Java SDK seja pelo menos `2.22.6`[Instalar o SDK] (/api-reference/preparation/install-sdk).



```java
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;

public class Image2Video {

  static {
    Constants.baseHttpApiUrl = "https://maas.qwencloudapi.com/api/v1";
  }

  // If you have not set an environment variable, replace the line below with: apiKey="sk-xxx"
  static String apiKey = System.getenv("DASHSCOPE_API_KEY");

  public static void image2video() throws ApiException, NoApiKeyException, InputRequiredException {
    VideoSynthesis vs = new VideoSynthesis();
    VideoSynthesisParam param =
        VideoSynthesisParam.builder()
            .apiKey(apiKey)
            .model("wan2.2-kf2v-flash")
            .prompt("Realistic style. A curious black kitten looks up at the sky. The camera starts at eye level and gradually rises until it captures the kitten's curious gaze from above.")
            .firstFrameUrl("https://wanx.alicdn.com/material/20250318/first_frame.png")
            .lastFrameUrl("https://wanx.alicdn.com/material/20250318/last_frame.png")
            .resolution("720P")
            .promptExtend(true)
            .watermark(true)
            .build();
    // Asynchronous call
    VideoSynthesisResult task = vs.asyncCall(param);
    System.out.println(JsonUtils.toJson(task));
    System.out.println("please wait...");

    // Get result
    VideoSynthesisResult result = vs.wait(task, apiKey);
    System.out.println(JsonUtils.toJson(result));
  }

  public static void main(String[] args) {
    try {
      image2video();
    } catch (ApiException | NoApiKeyException | InputRequiredException e) {
      System.out.println(e.getMessage());
    }
    System.exit(0);
  }
}
```

curl

 Passo 1: Crie uma tarefa para obter a identificação da tarefa

```bash
curl --location 'https://maas.qwencloudapi.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": "Realistic style. A curious black kitten looks up at the sky. The camera starts at eye level and gradually rises until it captures the kitten's curious gaze from above."
  },
  "parameters": {
    "resolution": "720P",
    "prompt_extend": true,
    "watermark": true
  }
}'
```

 Passo 2: Obtenha o resultado usando a identificação da tarefa

 Substituir `{task_id}` com o `task_id` O valor retornado pela chamada anterior da API.

```bash
curl -X GET https://maas.qwencloudapi.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
```

Imagem de entrada

Method 2: Local file path (SDK only)

Linguagens de programação diferentes (Python e Java) têm diferentes requisitos de caminho. Siga as regras abaixo exatamente.

Python SDK: suporta caminhos absolutos e relativos. Regras do caminho:

Sistema operacional. Caminho do arquivo de entrada Exemplo (caminho absoluto) Exemplo (caminho relativo)
Linux / macOS Arquivo: Arquivo: Arquivo:///images/test.png
Janelas Arquivo: Arquivo: / imagens / teste. png Arquivo:///images/test.png

Apenas caminhos absolutos. Regras do caminho:

Sistema operacional. Caminho do arquivo de entrada Exemplo (caminho absoluto)
Linux / macOS arquivo: Arquivo:
Janelas Arquivo: Arquivo: / D: / imagens / teste. png

Código de exemplo: múltiplos métodos de entrada de imagens.

Python SDK

```python
import os
from http import HTTPStatus
# dashscope sdk >= 1.25.8
from dashscope import VideoSynthesis
import dashscope

dashscope.base_http_api_url = 'https://maas.qwencloudapi.com/api/v1'

# Get the DashScope API key (API key) from the environment variable
api_key = os.getenv("DASHSCOPE_API_KEY")

# ========== Image input method (choose one) ==========
# [Method 1] Use a public image 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"

# [Method 2] Use a local file path (file:// + file path)
# Use an absolute path
# first_frame_url = "file://" + "/path/to/your/first_frame.png"  # Linux/macOS
# last_frame_url = "file://" + "C:/path/to/your/last_frame.png"  # Windows
# Or use a relative path
# first_frame_url = "file://" + "./first_frame.png"              # Use your actual path
# last_frame_url = "file://" + "./last_frame.png"                # Use your actual path

def sample_sync_call_kf2v():
  print('please wait...')
  rsp = VideoSynthesis.call(api_key=api_key,
                                model="wan2.2-kf2v-flash",
                                prompt="Realistic style, 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.",
                                first_frame_url=first_frame_url,
                                last_frame_url=last_frame_url,
                                resolution="720P",
                                prompt_extend=True)
  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_sync_call_kf2v()
```

Java SDK

```java
// Copyright (c) Alibaba, Inc. and its affiliates.

// dashscope sdk >= 2.20.1
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.util.HashMap;
import java.util.Map;

public class Kf2vSyncIntl {

  static {
    Constants.baseHttpApiUrl = "https://maas.qwencloudapi.com/api/v1";
  }

  // Get the DashScope API key (API key) from the environment variable
  static String apiKey = System.getenv("DASHSCOPE_API_KEY");

  /**
       * Image input method (choose one):
       *
       * [Method 1] Public URL
       */
  static String firstFrameUrl = "https://wanx.alicdn.com/material/20250318/first_frame.png";
  static String lastFrameUrl = "https://wanx.alicdn.com/material/20250318/last_frame.png";

       /**
       * [Method 2] Local file path (file:// + absolute path or file:/// + absolute path)
       */
  // static String firstFrameUrl = "file://" + "/your/path/to/first_frame.png";  // Linux/macOS
  // static String lastFrameUrl = "file:///" + "C:/path/to/your/img.png";        // Windows

  public static void syncCall() {

    Map<String, Object> parameters = new HashMap<>();
    parameters.put("prompt_extend", true);
    parameters.put("resolution", "720P");

    VideoSynthesis videoSynthesis = new VideoSynthesis();
    VideoSynthesisParam param =
        VideoSynthesisParam.builder()
            .apiKey(apiKey)
            .model("wan2.2-kf2v-flash")
            .prompt("Realistic style, 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.")
            .firstFrameUrl(firstFrameUrl)
            .lastFrameUrl(lastFrameUrl)
            .parameters(parameters)
            .build();
    VideoSynthesisResult result = null;
    try {
      System.out.println("---sync call, please wait a moment----");
      result = videoSynthesis.call(param);
    } catch (ApiException | NoApiKeyException e){
      throw new RuntimeException(e.getMessage());
    } catch (InputRequiredException e) {
      throw new RuntimeException(e);
    }
    System.out.println(JsonUtils.toJson(result));
  }

  public static void main(String[] args) {
    syncCall();
  }
}
```

Vídeo de saída

Referência da API

FAQ

Como posso gerar um vídeo com uma proporção de aspecto específica (como 3:4)?

**wan2.7A proporção de aspecto é determinada pela imagem do primeiro quadro. Quando... first_frame é fornecido no media Array, o ratio O parâmetro é ignorado e a saída corresponde à proporção de aspecto da imagem.

**wan2.2 A API não suporta especificar as proporções de aspecto diretamente. Você só pode definir a resolução de vídeo usando o resolution parâmetro.

O resolution O parâmetro controla a contagem total de pixels, não a relação de aspecto estrita. O modelo prioriza preservar a proporção de aspecto original da imagem de primeira estrutura (first_frame_url) e faz pequenos ajustes para atender aos requisitos de codificação (largura e altura devem ser múltiplos de 16). Para obter um vídeo perto das 3:4, carregue uma imagem de primeira imagem com uma proporção de 3:4.

Por exemplo, a imagem de entrada é de 750x1000 (taxa de variação 3:4 = 0,75). Resolução definida = 720P (o alvo é de aproximadamente 920.000 pixels). Saída pode ser 816 x 1104 (taxa de aproximação aproximadamente 0,739, contagem de pixels aproximadamente 900.000), com ambas as dimensões divisíveis por 16.

Erro SDK: "erro de url, por favor verifique url!"

Certifique-se:

Se sua versão é muito baixa, você pode ver o "erro de url, por favor verifique url!" erro./api-reference/preparation/install-sdk).