To obtain a video thumbnail, extract keyframes for video editing, or extract frames for specific scenarios such as video monitoring, you can upload the video to an OSS bucket and use the video snapshot feature to extract keyframe images.
Precautions
You can take snapshots only of videos that are encoded in H.264 or H.265.
By default, OSS does not save the images captured from video snapshots. You must manually download the images and save them to your local computer.
You are charged for the video snapshot feature based on the number of images captured. For more information about billing, see Data processing fees.
How to use
Prerequisites
You have created a bucket in OSS and uploaded the frame-capture video to it.
Take a video snapshot
In OSS, when you include the ?x-oss-process=video/snapshot,parame_value
parameter in a request, OSS processes the video in real time and returns the result. video/snapshot
specifies the video snapshot action. parame
specifies the parameter, and value
specifies the value for that parameter. For more information about the parameters, see Parameters in this topic. You can specify multiple parameters in a single request.
For public-read videos, you can add processing parameters to the file URL to allow anonymous users to permanently access the URL of the processed file. If your video is private, you must use an SDK to call an operation and include a signature to process the video.
Public-read files
To take a snapshot of a public-read file, add the ?x-oss-process=video/snapshot,parame_value
parameter to its URL. You must replace parame_value
with the required parameters and values.
Original URL | URL with processing parameters |
Private files
You can use an OSS SDK to generate a signed URL that contains processing parameters. This allows users who have the URL to temporarily access the processed video. The following code provides examples of how to use an SDK to generate a signed URL that contains 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 {
// Set the endpoint. In this example, the endpoint of the China (Hangzhou) region is used. Specify the actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 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.
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, the path must include the directory where the video file is stored. Example: examplefolder/videotest.mp4.
String objectName = "examplefolder/videotest.mp4";
// Specify the region in which the bucket is located. In this example, the China (Hangzhou) region is used. 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 the 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 accurate snapshot mode to capture a snapshot at 17 seconds of the video. The snapshot is in the JPG format, and the width and height are 800 and 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 you run 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 in which the bucket is located. In this example, the China (Hangzhou) region is used.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the general-purpose region ID of Alibaba Cloud.
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, the path must include the directory where the video file is stored. Example: examplefolder/videotest.mp4.
key = 'examplefolder/videotest.mp4'
# Specify the expiration time in seconds.
expire_time = 3600
# Use the accurate snapshot mode to capture a snapshot at 17 seconds of the video. The snapshot is in the JPG format, and the width and height are 800 and 600.
image_process = 'video/snapshot,t_17000,f_jpg,w_800,h_600'
# Generate a signed URL that contains 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 you run 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 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, the path must include the directory where the video file is stored. 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 that contains processing parameters. The URL is valid for 3600 seconds. You can use a browser to access the URL.
$timeout = 3600;
$options = array(
// Use the accurate snapshot mode to capture a snapshot at 17 seconds of the video. The snapshot is in the JPG format, and the width and height are 800 and 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 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 bucket. In this example, the endpoint of the China (Hangzhou) region is used. Set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify the actual endpoint.
// Set yourRegion to the region in which the bucket is located. In this example, the China (Hangzhou) region is used. Set the region to cn-hangzhou. Specify the actual region.
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 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 file. If the video file is not in the root directory of the bucket, the path must include the directory where the video file is stored. Example: examplefolder/videotest.mp4.
ossName := "examplefolder/videotest.mp4"
// Generate a signed URL and set the expiration time to 3600s.
// Use the accurate snapshot mode to capture a snapshot at 17 seconds of the video. The snapshot is in the JPG format, and the width and height are 800 and 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({
// Set yourregion to the region in which the bucket is located. In this example, the China (Hangzhou) region is used. 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,
// Set yourbucketname to the bucket name.
bucket: "examplebucket",
});
// Processing 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 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 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 video is stored. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the name. If the video is not in the root directory of the bucket, you must specify the full path of the file.
var objectName = "examplefolder/videotest.mp4";
// Specify the region in which the bucket is located. In this example, the China (Hangzhou) region is used. Set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your needs.
var conf = new ClientConfiguration();
// Set the signature to V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Take a 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"
/* Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is 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. The full path cannot contain the bucket name. */
const char *object_name = "examplefolder/videotest.mp4";
/* Set yourRegion to the region in which the bucket is located. In this example, the China (Hangzhou) region is used. 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);
/* Initialize the aos_string_t type with a char* string. */
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"));
// You must configure the following two parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specifies whether a CNAME is used. 0 indicates that no CNAME is used. */
options->config->is_cname = 0;
/* Set 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 at the program entry to initialize global resources such as the network and memory. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* The memory pool (pool) for memory management is 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, which indicates that no other memory pools are inherited. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. The options include 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 to options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client option 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 (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 is equivalent to releasing the memory allocated to resources during the request. */
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. */
/* Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region in which the bucket is located. In this example, the China (Hangzhou) region is used. Set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the name of the bucket in which the video is stored. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the video name. If the image is not in the root directory of the bucket, you must specify the full path of the file. */
std::string ObjectName = "examplefolder/videotest.mp4";
/* Initialize resources such as the network. */
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 that contains 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 the network. */
ShutdownSdk();
return 0;
}
The following sample code shows an example of a 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=6fd07a2ba50bf6891474dc56aed976b556b6fbcd901cfd01bcde5399bf4802cb
Parameters
Action: video/snapshot
Parameter | Description | Valid values |
t | The time when the snapshot is captured. If the specified time exceeds the video duration, the last keyframe of the video is returned. Note If you want to capture a video thumbnail, set t to 0. | [0, Video duration] Unit: ms |
w | The width of the snapshot. If you set this parameter to 0, the width is calculated based on the ratio of the snapshot height to the source video height. | [0, Video width] Unit: pixel (px) |
h | The height of the snapshot. If you set this parameter to 0, the height is calculated based on the ratio of the snapshot width to the source video width. If both w and h are set to 0, the snapshot has the same width and height as the source video. | [0, Video height] Unit: pixel (px) |
m | The snapshot mode. If you do not specify this parameter, the default mode is used to capture a snapshot at a specified point in time. If you set this parameter to fast, the nearest keyframe before the specified point in time is captured. | Enumeration value: fast |
f | The format of the output image. | Enumeration values: jpg and png |
ar | Specifies whether to automatically rotate the image based on the video information. | Enumeration values: auto, h, and w The following list describes the enumeration values:
|