Video snapshot

更新时间:
复制 MD 格式

When you need to obtain a video thumbnail, extract key frames for video editing, or extract specific scene frames for video monitoring, you can upload the video to an OSS bucket and extract key frames using the video snapshot feature.

Notes

  • OSS can capture snapshots from videos only in the H.264 and H.265 formats.

  • By default, OSS does not automatically store captured snapshots. You must manually download captured snapshots to your local storage devices.

  • When you capture video snapshots, you are charged based on the number of captured snapshots. For more information, see Data processing fees.

How to use

Prerequisites

You have created a bucket in OSS and uploaded the video that you want to capture snapshots from 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 processed result. video/snapshot indicates video snapshot processing. parame represents the supported parameters, and value represents the parameter value. Detailed parameter descriptions are provided in the Parameter description section below. Multiple parameters can be used in combination.

For public-read videos, you can directly add processing parameters to the file URL to allow anyone to access the processed file URL anonymously and permanently. If your video is private, you need to call the SDK with signature information to process the video.

Obtain the URL of a public-read object

The following describes how to add 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

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

Private files

You can use OSS SDK to generate a signed URL with processing parameters, allowing users with this URL to temporarily access the processed video. The following examples show how to use 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 {
        // 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;
}

The following sample code provides an example on how to generate a 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

Parameter description

Action: video/snapshot

Parameter

Description

Value range

t

The point in time at which you want to capture the snapshot. If the value exceeds the length of the video, the last frame is returned.

Note

If you want to capture a video thumbnail, set t to 0.

[0, video duration]

Unit: milliseconds

w

The width of the snapshot to capture. If this parameter is set to 0, the width of the captured snapshot is calculated based on the proportion of the height of the captured snapshot to the video height.

[0, video width]

Unit: pixels

h

The height of the snapshot to capture. If this parameter is set to 0, the height is automatically calculated based on the proportion of the width of the captured snapshot to the video width. If both w and h are set to 0, the output image has the same width and height as the original video.

[0, video height]

Unit: pixels

m

The mode used to capture the snapshot. If this parameter is not specified, the snapshot is captured in the default mode. In other words, the snapshot at the specified point in time of the video is captured. If this parameter is set to fast, the most recent keyframe before the specified point in time is captured.

Enumeration value: fast

f

The format of the snapshot to return.

Enumeration values: jpg and png

ar

Specifies whether to automatically rotate the captured snapshot based on the video information.

Enumeration values: auto, h, and w

The following list describes the enumeration values:

  • auto: automatically rotates the snapshot based on the video information after the snapshot is captured.

  • h: forcibly rotates the snapshot based on the video information after the snapshot is captured so that the height is greater than the width.

  • w: forcibly rotates the snapshot based on the video information after the snapshot is captured so that the width is greater than the height.

Examples

Use the default mode to capture an image

The following example shows how to add the ?x-oss-process=video/snapshot,t_17000,f_jpg,w_800,h_600 parameter to use the default accurate time mode to capture an image at the 17th second of the video.d image is in JPG format with a width of 800 pixels and a height of 600 pixels:

Original URL

URL with processing parameters

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

The captured snapshot is as follows:

2

Use the fast mode to capture an image

The following example shows how to add the ?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast parameter to use the fast mode to capture an image at the 7th second of the video. The captured image is in JPG format with a width of 800 pixels and a height of 600 pixels:

Original URL

URL with processing parameters

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

The captured snapshot is as follows:

1

FAQ

Can I process a video object whose ACL is private by directly adding parameters to the URL of the object?

No. If the ACL of the video object that you want to process is private, you can use OSS SDKs to add video processing operations to the signed URL of the object. You cannot process a video object whose ACL is private by directly adding parameters to the object URL.

How do I view the width and height of a video object that is stored in OSS?

You can use the video information extraction feature to obtain the width and height of a video.

The captured snapshot appears distorted

Currently, OSS does not support capturing snapshots from Dolby Vision source videos.

Can I obtain a video thumbnail through video snapshot in OSS, and how can I make it permanent?

Yes. After obtaining the thumbnail, you can upload it to OSS as a network stream. OSS will generate a snapshot file, which can then be permanently stored.