Para obter uma miniatura de vídeo, extrair quadros-chave para edição ou capturar cenas específicas para monitoramento, carregue o vídeo em um bucket do OSS e use o recurso de snapshot de vídeo para extrair os quadros desejados.
Observações
O OSS captura snapshots apenas de vídeos nos formatos H.264 e H.265.
Por padrão, o OSS não armazena automaticamente os snapshots capturados. Baixe manualmente os snapshots para seus dispositivos de armazenamento local.
A cobrança pela captura de snapshots de vídeo baseia-se na quantidade de snapshots gerados. Para mais informações, consulte Taxas de processamento de dados.
Como usar
Pré-requisitos
Você já criou um bucket no OSS e carregou o vídeo do qual deseja capturar snapshots nesse bucket.
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. video/snapshot indica o processamento de snapshot de vídeo. parame representa os parâmetros suportados e value representa o valor do parâmetro. A seção Descrição dos parâmetros detalha cada parâmetro. É possível combinar vários parâmetros.
Para vídeos com leitura pública, adicione os parâmetros de processamento diretamente à URL do arquivo. Isso permite que qualquer pessoa acesse a URL do arquivo processado de forma anônima e permanente. Se o vídeo for privado, chame o SDK com informações de assinatura para processar o vídeo.
Obter a URL de um objeto de leitura pública
O exemplo a seguir mostra como adicionar o parâmetro ?x-oss-process=video/snapshot,parame_value à URL de um arquivo de leitura pública. Substitua parame_value pelos parâmetros e valores específicos conforme 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 |
Arquivos privados
Use o SDK do OSS para gerar uma URL assinada com parâmetros de processamento. Isso permite que usuários com essa URL acessem temporariamente o vídeo processado. Os exemplos a seguir demonstram como usar o 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 {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain a credential from the environment variables. Before you run 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 name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the video object. If the video object is not stored in the root directory of the bucket, you must provide the full path of the object. Example: examplefolder/videotest.mp4.
String objectName = "examplefolder/videotest.mp4";
// Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// When the OSSClient instance is no longer used, 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 {
// Accurately capture the snapshot at the 17th second of the video. Export the captured snapshot as a JPG image whose width is 800 pixels and height is 600 pixels.
String style = "video/snapshot,t_17000,f_jpg,w_800,h_600";
// Set the validity period of the signed URL to 3600 seconds)
Date expiration = new Date(new Date().getTime() + 3600 );
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 a credential from the environment variables. Before you execute 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 name of the bucket
bucket = 'examplebucket'
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the ID of the Alibaba Cloud region in which the bucket is located
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, bucket, region=region)
# Specify the full path of the video object. If the video object is not stored in the root directory of the bucket, you must provide the full path to the object. Example: examplefolder/videotest.mp4.
key = 'examplefolder/videotest.mp4'
# Specify the expiration time. Unit: seconds
expire_time = 3600
# Capture the snapshot right at the 17th second of the video. Export the captured snapshot as a JPG image whose width is 800 pixels and height is 600 pixels.
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 a credential from the environment variables. Before you execute the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to the endpoint of the region in which 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 name of the bucket. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the video object. If the video object is not stored in the root directory of the bucket, you must provide the full path of the object. 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 that is valid for 3600 seconds and can be accessed directly from a browser.
$timeout = 3600;
$options = array(
// Capture the snapshot right at the 17th second of the video. Export the captured snapshot as a JPG image whose width is 800 pixels and height is 600 pixels.
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 you run 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.
// Set yourEndpoint to the endpoint of the region in which 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 your actual endpoint.
// Specify the region of the bucket. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify your actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify 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 in which the image is stored. Example: examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
HandleError(err)
}
// Specify the full path of the video object. If the video object is not stored in the root directory of the bucket, you must include the directory of the object in the path. Example: examplefolder/videotest.mp4.
ossName := "examplefolder/videotest.mp4"
// Generate a signed URL that includes IMG parameters. Set the validity period of the URL to 3,600 seconds.
// Capture the snapshot right at the 17th second of the video. Export the captured snapshot as a JPG image whose width is 800 pixels and height is 600 pixels.
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 in which 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 you run 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 name of the bucket.
bucket: "examplebucket",
});
// Process 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;
// Set yourEndpoint to the endpoint of the region in which 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 a credential from the environment variables. Before you run 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 in which the source image is stored. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the name. If the video is not in the root directory of the bucket, include the full path of the file.
var objectName = "examplefolder/videotest.mp4";
// Specify the region in which 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 based on your requirements.
var conf = new ClientConfiguration();
// Specify the V4 signature algorithm.
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 a 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 in which 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 name of the bucket. Example: examplebucket.*/
const char *bucket_name = "examplebucket";
/* Specify the full path of the Object. The full path cannot contain the bucket name.*/
const char *object_name = "examplefolder/videotest.mp4";
/* Specify the region in which 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 aos_string_t.*/
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run 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"));
// Specify two additional parameters
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether to use CNAME. A value of 0 indicates that CNAME is not used.*/
options->config->is_cname = 0;
/* Configure network 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 in main() to initialize global resources such as networks and memory.*/
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* Create a pool for memory management. aos_pool_t is equivalent to apr_pool_t.*/
aos_pool_t *pool;
/* Create a memory pool. The second parameter is NULL. This value indicates that the pool does not inherit other memory pools.*/
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configuration information such as endpoint, access_key_id, access_key_secret, is_cname, and curl.*/
oss_request_options_t *oss_client_options;
/* Allocate memory resources in the memory pool to the options parameter.*/
oss_client_options = oss_request_options_create(pool);
/* Initialize Client's 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 validity period (expire_time) in seconds.*/
now = apr_time_now();
expire_time = now / 1000000 + 10 * 60;
/* Generate a 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. This operation releases memory resources allocated for the request.*/
aos_pool_destroy(pool);
/* Release resources such as network resources.*/
aos_http_io_deinitialize();
return 0;
}
C++
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the information about the account that is used to access OSS.*/
/* Specify the endpoint of the region in which 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 in which 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 in which the source image is stored. Example: examplebucket.*/
std::string BucketName = "examplebucket";
/* Specify the name of the video. If the image is not in the root directory of the bucket, include the full path of the file.*/
std::string ObjectName = "examplefolder/videotest.mp4";
/* Initialize resources such as networks.*/
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run 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 for the file with processing parameters.*/
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 resources such as network resources.*/
ShutdownSdk();
return 0;
}
O código de exemplo a seguir mostra como gerar uma URL assinada:
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
Ação: video/snapshot
Parâmetro | Descrição | Faixa de valores |
t | Momento exato para capturar o snapshot. Se o valor exceder a duração do vídeo, o último quadro será retornado. Nota Para capturar uma miniatura do vídeo, defina t como 0. | [0, duração do vídeo] Unidade: milissegundos |
w | Largura do snapshot a ser capturado. Se definido como 0, a largura será calculada proporcionalmente à altura do snapshot em relação à altura do vídeo. | [0, largura do vídeo] Unidade: pixels |
h | Altura do snapshot a ser capturado. Se definida como 0, a altura será calculada automaticamente com base na proporção entre a largura do snapshot e a largura do vídeo. Se w e h forem definidos como 0, a imagem de saída terá a mesma largura e altura do vídeo original. | [0, altura do vídeo] Unidade: pixels |
m | Modo de captura do snapshot. Sem especificação, utiliza-se o modo padrão, capturando o quadro no momento exato indicado. Ao definir como fast, o sistema captura o quadro-chave mais próximo anterior ao momento especificado. | Valor de enumeração: fast |
f | Formato de retorno do snapshot. | Valores de enumeração: jpg e png |
ar | Define se o snapshot capturado deve ser rotacionado automaticamente com base nas informações do vídeo. | Valores de enumeração: auto, h e w A lista a seguir descreve os valores de enumeração:
|