Video snapshots
You can upload videos to an OSS bucket and use the video snapshot feature to extract key frames when you need to obtain video thumbnails, extract key frames for video editing, or capture specific scene frames for video surveillance.
Usage notes
Video snapshots are supported only for video files encoded in H.264 and H.265.
OSS does not save video snapshot images by default. You must manually download and save the snapshot images to your local device.
When you use the video snapshot feature, you are billed based on the number of snapshot images captured. For more information about billing, see Data processing fees.
How to use
Prerequisites
Create a bucket in OSS, and upload the video for which you want to extract snapshots to the bucket.
Video snapshot
In OSS, when you include the ?x-oss-process=video/snapshot,parame_value parameter, OSS processes the video in real time and returns the result. video/snapshot indicates video snapshot processing. parame represents supported parameters, and value represents parameter values. Detailed parameter descriptions are provided in the Parameter description section below, and you can combine multiple parameters.
For public-read videos, you can directly append processing parameters to the file URL, allowing anyone to permanently and anonymously access the processed file URL. If your video is private, you must use an SDK to include signature information when processing the video.
Public-read files
The following describes how to append the ?x-oss-process=video/snapshot,parame_value parameter to a public-read file URL. You only need to replace parame_value with specific parameters and values based on your business requirements.
Original URL | URL with processing parameters |
https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/video.mp4 |
Private files
You can use an OSS SDK to generate a signed URL with processing parameters, allowing users who hold the URL to temporarily access the processed video. The following example shows how to use an SDK to generate a signed URL with the ?x-oss-process=video/snapshot_value parameter for a private video:
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;
}The following shows an example of the generated signed URL:
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=6fd07a2ba50bf6891474dc56aed976b556b6fbcd901cfd01bcde5399bf4802cbParameter description
Operation name: video/snapshot
Parameter | Description | Value range |
t | Specifies the snapshot time. If the specified snapshot time t exceeds the video duration, the last key frame of the video is returned. Note To capture a video thumbnail, set t to 0. | [0, Video duration] Unit: ms |
w | Specifies the width of the snapshot. If set to 0, the width is automatically calculated based on the ratio of the snapshot height to the source video height. | [0, Video width] Unit: pixel (px) |
h | Specifies the height of the snapshot. If set to 0, the height is automatically calculated based on the ratio of the snapshot width to the source video width. If both w and h are set to 0, the output uses the original video width and height. | [0, Video height] Unit: pixel (px) |
m | Specifies the snapshot mode. If not specified, the default mode is used and the snapshot is captured at the exact time. If set to fast, the nearest key frame before the specified time point is captured. | Enumeration value: fast |
f | Specifies the output image format. | Enumeration values: jpg and png |
ar | Specifies whether to automatically rotate the image based on video information. | Enumeration values: auto, h, and w Description of each enumeration value:
|