Todos os produtos
Search
Central de documentação

Object Storage Service:Video snapshots

Última atualização: Oct 09, 2026

Faça upload de vídeos para um bucket do OSS e use o recurso de snapshot de vídeo para extrair quadros-chave. Esse recurso é ideal para obter miniaturas de vídeo, extrair quadros para edição ou capturar cenas específicas em sistemas de videomonitoramento.

Observações de uso

  • Snapshots de vídeo são suportados apenas para arquivos de vídeo codificados em H.264 e H.265.

  • O OSS não salva as imagens de snapshot de vídeo por padrão. Baixe e salve manualmente as imagens de snapshot no seu dispositivo local.

  • Ao usar o recurso de snapshot de vídeo, a cobrança ocorre com base na quantidade de imagens de snapshot capturadas. Para mais informações sobre o faturamento, consulte Taxas de processamento de dados.

Como usar

Pré-requisitos

Criar um bucket no OSS e fazer upload do vídeo para o bucket do qual você deseja extrair os snapshots.

Snapshot de vídeo

No OSS, ao incluir o parâmetro ?x-oss-process=video/snapshot,parame_value, o serviço processa o vídeo em tempo real e retorna o resultado. O termo video/snapshot indica o processamento de snapshot de vídeo. O termo parame representa os parâmetros aceitos, e value representa os valores desses parâmetros. As descrições detalhadas estão na seção Descrição dos parâmetros abaixo. É possível combinar vários parâmetros.

Para vídeos de leitura pública, anexe os parâmetros de processamento diretamente à URL do arquivo. Isso permite que qualquer pessoa acesse a URL do arquivo processado de forma permanente e anônima. Se o vídeo for privado, use um SDK para incluir as informações de assinatura ao processar o vídeo.

Arquivos de leitura pública

A seguir, veja como anexar o parâmetro ?x-oss-process=video/snapshot,parame_value à URL de um arquivo de leitura pública. Basta substituir parame_value pelos parâmetros e valores específicos de acordo com as necessidades do seu negócio.

URL original

URL com parâmetros de processamento

https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/video.mp4

https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/video.mp4?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast

Arquivos privados

Use um SDK do OSS para gerar uma URL assinada com parâmetros de processamento. Isso permite que os usuários com a URL acessem temporariamente o vídeo processado. O exemplo a seguir mostra como usar um SDK para gerar uma URL assinada com o parâmetro ?x-oss-process=video/snapshot_value para um vídeo privado:

Java

package com.aliyun.oss.demo;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import java.net.URL;
import java.util.Date;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint based on your requirements.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before running the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. Example: examplebucket.
        String bucketName = "examplebucket";
        // Specify the full path of the video file. If the video file is not in the root directory of the bucket, include the file path. Example: examplefolder/videotest.mp4.
        String objectName = "examplefolder/videotest.mp4";
        // Specify the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When you no longer need the OSSClient instance, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Use the exact time mode to capture a snapshot at the 17s position of the video, and output it as a JPG image with a width of 800 and a height of 600.
            String style = "video/snapshot,t_17000,f_jpg,w_800,h_600";
            // Specify the expiration time of the signed URL.
            Date expiration = new Date(new Date().getTime() + 3600 * 1000L );
            GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
            req.setExpiration(expiration);
            req.setProcess(style);
            URL signedUrl = ossClient.generatePresignedUrl(req);
            System.out.println(signedUrl);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Python

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before running the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the bucket name.
bucket = 'examplebucket'

# Specify the endpoint of the region where the bucket is located. In this example, the China (Hangzhou) region is used.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'

# Specify the Alibaba Cloud region ID.
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, bucket, region=region)

# Specify the full path of the video file. If the video file is not in the root directory of the bucket, include the file path. Example: examplefolder/videotest.mp4.
key = 'examplefolder/videotest.mp4'

# Specify the expiration time in seconds.
expire_time = 3600

# Use the exact time mode to capture a snapshot at the 17s position of the video, and output it as a JPG image with a width of 800 and a height of 600.
image_process = 'video/snapshot,t_17000,f_jpg,w_800,h_600'

# Generate a signed URL with processing parameters.
url = bucket.sign_url('GET', key, expire_time, params={'x-oss-process': image_process}, slash_safe=True)

# Print the signed URL.
print(url)

PHP

<?php

if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;

// Obtain access credentials from environment variables. Before running the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$provider = new EnvironmentVariableCredentialsProvider();
// Specify the endpoint of the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Specify the bucket name. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the video file. If the video file is not in the root directory of the bucket, include the file path. Example: examplefolder/videotest.mp4.
$object = "examplefolder/videotest.mp4";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

// Generate a signed URL with processing parameters. The URL is valid for 3600 seconds and can be directly accessed through a browser.
$timeout = 3600;

$options = array(
    // Use the exact time mode to capture a snapshot at the 17s position of the video, and output it as a JPG image with a width of 800 and a height of 600.
    OssClient::OSS_PROCESS => "video/snapshot,t_17000,f_jpg,w_800,h_600");

$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
print("url: \n" . $signedUrl);

Go

package main

import (
	"fmt"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func HandleError(err error) {
	fmt.Println("Error:", err)
	os.Exit(-1)
}

func main() {
	// Obtain access credentials from environment variables. Before running the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Create an OSSClient instance.
	// Specify the endpoint of the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
	// Specify the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		HandleError(err)
	}

	// Specify the name of the bucket. Example: examplebucket.
	bucketName := "examplebucket"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		HandleError(err)
	}
	// Specify the full path of the video file. If the video file is not in the root directory of the bucket, include the file path. Example: examplefolder/videotest.mp4.
	ossName := "examplefolder/videotest.mp4"
	// Generate a signed URL with an expiration time of 3600 seconds.
	// Use the exact time mode to capture a snapshot at the 17s position of the video, and output it as a JPG image with a width of 800 and a height of 600.
	signedURL, err := bucket.SignURL(ossName, oss.HTTPGet, 3600, oss.Process("video/snapshot,t_17000,f_jpg,w_800,h_600"))
	if err != nil {
		HandleError(err)
	} else {
		fmt.Println(signedURL)
	}
}

Node.js

const OSS = require("ali-oss");

const client = new OSS({
  // Specify the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: "oss-cn-hangzhou",
  // Obtain access credentials from environment variables. Before running the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the bucket name.
  bucket: "examplebucket",
});
// Process the video with the style "video/snapshot,t_17000,f_jpg,w_800,h_600".
const signUrl = client.signatureUrl("examplefolder/videotest.mp4", {
  expires: 3600,
  process: "video/snapshot,t_17000,f_jpg,w_800,h_600",
});
console.log("signUrl=" + signUrl);

.NET

using Aliyun.OSS;
using Aliyun.OSS.Common;

// Specify the endpoint of the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before running the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the name of the object. If the video is not in the root directory of the bucket, include the full file path.
var objectName = "examplefolder/videotest.mp4";
// Specify the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();

// Set the V4 signature.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // Video snapshot.
    var process = "video/snapshot,t_17000,f_jpg,w_800,h_600";
    var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get)
    {
        Expiration = DateTime.Now.AddHours(1),
        Process = process
    };
    // Generate the signed URI.
    var uri = client.GeneratePresignedUri(req);
    Console.WriteLine("Generate Presigned Uri:{0} with process:{1} succeeded ", uri, process);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}

C

#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the bucket name. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. */
const char *object_name = "examplefolder/videotest.mp4";
/* Specify the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Use a char* string to initialize an aos_string_t type. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before running the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    // The following two parameters must also be configured.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specifies whether to use CNAME. 0 indicates that CNAME is not used. */
    options->config->is_cname = 0;
    /* Configure network-related parameters such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method at the program entry to initialize global resources such as network and memory. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* Memory pool for memory management, equivalent to apr_pool_t. The implementation code is in the apr library. */
    aos_pool_t *pool;
    /* Create a memory pool. The second parameter is NULL, indicating that no other memory pool is inherited. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information such as endpoint, access_key_id, acces_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate memory for the options in the memory pool. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize the client options oss_client_options. */
    init_options(oss_client_options);
    /* Initialize parameters. */
    aos_string_t bucket;
    aos_string_t object;
    aos_table_t *params = NULL;
    aos_http_request_t *req;
    char *url_str;
    apr_time_t now;
    int64_t expire_time;
    aos_str_set(&bucket, bucket_name);
    aos_str_set(&object, object_name);
    params = aos_table_make(pool, 1);
    apr_table_set(params, OSS_PROCESS, "video/snapshot,t_17000,f_jpg,w_800,h_600");
    req = aos_http_request_create(pool);
    req->method = HTTP_GET;
    req->query_params = params;
    /* Specify the expiration time in seconds. */
    now = apr_time_now();
    expire_time = now / 1000000 + 10 * 60;
    /* Generate the signed URL. */
    url_str = oss_gen_signed_url(oss_client_options, &bucket, &object, expire_time, req);
    printf("url: %s\n", url_str);
    /* Release the memory pool, which releases the memory allocated for resources during the request process. */
    aos_pool_destroy(pool);
    /* Release the previously allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}

C++

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize OSS account information. */

    /* Specify the endpoint of the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the name of the video. If the video is not in the root directory of the bucket, include the full file path. */
    std::string ObjectName = "examplefolder/videotest.mp4";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before running the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Generate a signed URL with processing parameters for the file. */
    std::string Process = "video/snapshot,t_17000,f_jpg,w_800,h_600";
    GeneratePresignedUrlRequest request(BucketName, ObjectName, Http::Get);
    request.setProcess(Process);
    auto outcome = client.GeneratePresignedUrl(request);

    if (outcome.isSuccess()) {
    std::cout << "Generated presigned URL: " << outcome.result() << std::endl;
    } else {
    std::cout << "Failed to generate presigned URL. Error code: " << outcome.error().Code()
              << ", Message: " << outcome.error().Message()
              << ", RequestId: " << outcome.error().RequestId() << std::endl;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

O exemplo a seguir mostra uma URL assinada gerada:

https://examplebucket.oss-cn-hangzhou.aliyuncs.com/examplefolder/videotest.mp4?x-oss-process=video%2Fsnapshot%2Ct_17000%2Cf_jpg%2Cw_800%2Ch_600&x-oss-date=20250311T083843Z&x-oss-expires=3600&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI********************%2F20241111%2Fcn-hangzhou%2Foss%2Faliyun_v4_request&x-oss-signature=6fd07a2ba50bf6891474dc56aed976b556b6fbcd901cfd01bcde5399bf4802cb

Descrição dos parâmetros

Nome da operação: video/snapshot

Parâmetro

Descrição

Intervalo de valores

t

Especifica o tempo do snapshot. Se o tempo t especificado exceder a duração do vídeo, o serviço retorna o último quadro-chave do vídeo.

Nota

Para capturar uma miniatura de vídeo, defina t como 0.

[0, Duração do vídeo]

Unidade: ms

w

Especifica a largura do snapshot. Se definido como 0, o serviço calcula a largura automaticamente com base na proporção entre a altura do snapshot e a altura do vídeo de origem.

[0, Largura do vídeo]

Unidade: pixel (px)

h

Especifica a altura do snapshot. Se definido como 0, o serviço calcula a altura automaticamente com base na proporção entre a largura do snapshot e a largura do vídeo de origem. Se tanto w quanto h forem definidos como 0, o resultado usa a largura e a altura originais do vídeo.

[0, Altura do vídeo]

Unidade: pixel (px)

m

Especifica o modo de snapshot. Se não for especificado, o serviço usa o modo padrão e captura o snapshot no tempo exato. Se definido como fast, o serviço captura o quadro-chave mais próximo antes do ponto de tempo especificado.

Valor de enumeração: fast

f

Especifica o formato da imagem de saída.

Valores de enumeração: jpg e png

ar

Especifica se o serviço gira a imagem automaticamente com base nas informações do vídeo.

Valores de enumeração: auto, h e w

Descrição de cada valor de enumeração:

  • auto: Gira a imagem automaticamente com base nas informações do vídeo após gerar o snapshot.

  • h: Força a rotação da imagem para a orientação retrato (altura maior que a largura) com base nas informações do vídeo após gerar o snapshot.

  • w: Força a rotação da imagem para a orientação paisagem (largura maior que a altura) com base nas informações do vídeo após gerar o snapshot.

Exemplos de uso

Capturar uma imagem usando o modo padrão

O exemplo a seguir usa o modo padrão de tempo exato para capturar um snapshot na posição de 17s do vídeo. Para isso, anexe o parâmetro ?x-oss-process=video/snapshot,t_17000,f_jpg,w_800,h_600 e gera um snapshot como uma imagem JPG com largura de 800 e altura de 600:

URL original

URL com parâmetros de processamento

https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/video.mp4

https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/video.mp4?x-oss-process=video/snapshot,t_17000,f_jpg,w_800,h_600

A imagem do snapshot é a seguinte:

2

Capturar uma imagem usando o modo rápido

O exemplo a seguir usa o modo rápido para capturar um snapshot. Para isso, anexe o parâmetro ?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast e gera um snapshot como uma imagem JPG com largura de 800 e altura de 600:

URL original

URL com parâmetros de processamento

https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/video.mp4

https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/video.mp4?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast

A imagem do snapshot é a seguinte:

1

Perguntas frequentes

Posso processar arquivos privados anexando parâmetros à URL?

Não. Para arquivos de vídeo privados que não permitem acesso anônimo, não é possível processar o vídeo ao anexar parâmetros diretamente à URL do arquivo. Use um SDK para incluir a operação de processamento de vídeo em uma URL assinada.

Como visualizar a largura e a altura de um vídeo no OSS?

Use o recurso Extração de informações de vídeo para obter a largura e a altura de um vídeo.

As imagens de snapshot de vídeo estão distorcidas

Atualmente, não há suporte para snapshots de vídeo em vídeos de origem Dolby Vision.

Posso obter uma miniatura de vídeo por meio de snapshot de vídeo e como torná-la permanente?

Sim. Após obter a miniatura, faça upload dela para o OSS por meio de um fluxo de rede. O OSS gerará um arquivo de snapshot e você pode salvar o arquivo permanentemente.