A Cascading Style Sheets (CSS) sprite is a collection of images combined into a single image file. Sprites are primarily used for website performance optimization and frontend development. You can use the CSS background-position property to reduce HTTP requests, which improves page load speed and user experience. You can use the sprite generation feature to extract video frames and combine them into a sprite. This topic describes the parameters for generating sprites from video snapshots and provides examples.
Usage notes
Generating sprites from video snapshots supports only asynchronous processing (x-oss-async-process).
Sprite generation may fail or produce an incorrect number of images if the video timestamp or stream is corrupted.
Before you use this feature, you must attach an IMM project. For more information about how to attach a project in the console or using an API, see Quick Start and AttachOSSBucket - Attach an OSS bucket.
Anonymous access will be denied.
You must have the required permissions to use the feature. For more information, see permissions.
Parameters
Action: video/sprite
The following table describes the parameters.
Parameter | Type | Required | Description |
ss | int | No | The start time for generating a sprite. Unit: millisecond. Valid values:
|
f | string | Yes | The output format of the sprite. Valid values:
Note The maximum resolution is 16384px × 16384px. |
m | string | No | The frame capture mode for sprite sub-images. The default value is inter. Valid values:
|
thr | int | No | The frame capture threshold for sprite sub-images in dhash mode. A larger threshold results in fewer captured frames. Valid values: [0, 100]. Default value: 0. Note This parameter is valid only in dhash mode. The dhash mode is sensitive to the threshold. Set this parameter to a value no greater than 25 and adjust it as needed. |
num | int | No | The number of frames to capture for sprite sub-images. Default value: 0, which indicates no limit on the number of captured frames. The default value has different meanings in different frame capture modes:
Important The actual number of captured frames may be less than the specified value due to the video length and frame capture parameters. |
inter | int | No | The interval for capturing frames for sprite sub-images. Unit: millisecond. Default value: 0, which indicates that all video frames are captured. Note If the value of this parameter is smaller than the frame interval (the reciprocal of the frame rate) of the source video, frames are captured based on the frame interval of the source video. |
sw | int | No | The width of a sprite sub-image. Unit: px. Valid values: [32, 4096]. By default, the sub-image width is the same as the source video width. |
sh | int | No | The height of a sprite sub-image. Unit: px. Valid values: [32, 4096]. By default, the sub-image height is the same as the source video height. |
psw | int | No | The percentage of the sprite sub-image width relative to the source video width. Valid values: (0, 200]. Default value: 100. Note If you set both the sw and psw parameters, the psw parameter does not take effect. |
psh | int | No | The percentage of the sprite sub-image height relative to the source video height. Valid values: (0, 200]. Default value: 100. Note If you set both the sh and psh parameters, the psh parameter does not take effect. |
scaletype | string | No | The scaling mode. Valid values:
|
tw | int | No | The number of sub-images in each row of the sprite. Default value: 6. Valid values: [1, 100]. |
th | int | No | The number of sub-images in each column of the sprite. Default value: 6. Valid values: [1, 100]. |
pad | int | No | The padding between sub-images in the sprite. Unit: px. Default value: 2. Valid values: [0, 100]. |
margin | int | No | The margin around the edges of the sprite. Unit: px. Default value: 2. Valid values: [0, 100]. |
The sys/saveas and notify parameters are also used when you generate sprites from video snapshots. For more information, see Save As and Notifications.
Use the REST API
If you do not specify a file extension, such as .jpg, in the storage path for the output sprite, the system automatically adds an ordinal number to the filename, such as _0_1.jpg. If you specify a file extension, only the last sprite is saved. Therefore, we recommend that you do not specify a file extension. To customize the ordinal number, use variables related to ApsaraVideo Media Processing.
Generate a sprite for the entire video by capturing one frame every 2 seconds
You can generate a sprite for the entire video by capturing one frame every 2 seconds. Each sprite contains a 3 × 3 grid of sub-images, and each sub-image has a resolution of 200 × 150.
Sprite information
Source file
Video name: example.mkv
Message notification
MNS topic for notifications: example-mns-topic
Output configuration
Frame capture information
Sprite format: jpg
Frame capture interval for sub-images: 2 s
Sub-image grid layout: 3 × 3
Sub-image resolution: 200 × 150
Sub-image scaling mode: crop
Padding between sub-images: 0
Margin around sub-images: 0
File storage path
JPG file: oss://outbucket/outobjprefix-%d.jpg
Example
// Generate a sprite from the example.mkv video file.
POST /exmaple.mkv?x-oss-async-process HTTP/1.1
Host: video-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e
x-oss-async-process=video/sprite,f_jpg,sw_200,sh_150,inter_2000,tw_3,th_3,pad_0,margin_0|sys/saveas,b_b3V0YnVja2V0,o_b3V0b2JqcHJlZml4LXtpbmRleH0ue2F1dG9leHR9Cg/notify,topic_ZXhhbXBsZS1tbnMtdG9waWMKGenerate a sprite by capturing frames at even intervals based on a specified number
You can generate a 10 × 10 sprite where the sub-images evenly cover the entire video. This simplifies frontend logic.
Sprite information
Source file
Video name: example.mkv
Message notification
MNS topic for notifications: example-mns-topic
Output configuration
Frame capture information
Sprite format: jpg
Frame capture mode for sub-images: avg
Sub-image grid layout: 10 × 10
Sub-image resolution: 1/10 of the source video
Sub-image scaling mode: fit
Padding between sub-images: 4
Margin around sub-images: 5
File storage path
JPG file: oss://outbucket/outobjprefix-%d.jpg
Example
// Generate a sprite from the example.mkv video file.
POST /exmaple.mkv?x-oss-async-process HTTP/1.1
Host: video-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e
x-oss-async-process=video/sprite,f_jpg,m_avg,psw_10,psh_10,scaletype_fit,tw_10,th_10,pad_4,margin_5|sys/saveas,b_b3V0YnVja2V0,o_b3V0b2JqcHJlZml4LXtpbmRleH0ue2F1dG9leHR9Cg/notify,topic_ZXhhbXBsZS1tbnMtdG9waWMKUse SDKs
Asynchronous sprite generation from video snapshots is supported only by the SDKs for Java, Python, and Go. For more information, see Install SDKs.
Java
OSS SDK for Java 3.17.4 or later is required.
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.AsyncProcessObjectRequest;
import com.aliyun.oss.model.AsyncProcessObjectResult;
import com.aliyuncs.exceptions.ClientException;
import java.util.Base64;
public class Demo {
public static void main(String[] args) throws ClientException {
// Specify the endpoint of the region where the bucket is located.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region ID that corresponds to the endpoint. Example: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run this 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.
String bucketName = "examplebucket";
// Specify the filename of the sprite.
String targetKey = "example.jpg";
// Specify the name of the source video file.
String sourceKey = "src.mp4";
// Create an OSSClient instance.
// When the OSSClient instance is no longer used, call the shutdown method to release its resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Configure the parameters for generating a sprite from a video.
String style = String.format("video/sprite,f_jpg,sw_100,sh_100,inter_10000,tw_10,th_10,pad_0,margin_0");
// Create an asynchronous processing instruction.
String bucketEncoded = Base64.getUrlEncoder().withoutPadding().encodeToString(bucketName.getBytes());
String targetEncoded = Base64.getUrlEncoder().withoutPadding().encodeToString(targetKey.getBytes());
String process = String.format("%s|sys/saveas,b_%s,o_%s/notify,topic_QXVkaW9Db252ZXJ0", style, bucketEncoded, targetEncoded);
// Create an AsyncProcessObjectRequest object.
AsyncProcessObjectRequest request = new AsyncProcessObjectRequest(bucketName, sourceKey, process);
// Execute the asynchronous processing task.
AsyncProcessObjectResult response = ossClient.asyncProcessObject(request);
System.out.println("EventId: " + response.getEventId());
System.out.println("RequestId: " + response.getRequestId());
System.out.println("TaskId: " + response.getTaskId());
} finally {
// Shut down the OSSClient.
ossClient.shutdown();
}
}
}Python
Python SDK 2.18.4 or later is required.
# -*- coding: utf-8 -*-
import base64
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Obtain temporary access credentials from environment variables. Before you run this 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 endpoint of the region where 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 = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the region ID that corresponds to the endpoint. Example: cn-hangzhou.
region = 'cn-hangzhou'
# Specify the bucket name.
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)
# Specify the name of the source video file.
source_key = 'src.mp4'
# Specify the filename of the sprite.
target_key = 'example.jpg'
# Configure the parameters for generating a sprite from a video.
animation_style = 'video/sprite,f_jpg,sw_100,sh_100,inter_10000,tw_10,th_10,pad_0,margin_0'
# Create a processing instruction that includes the storage path and the Base64-encoded bucket name and object name.
bucket_name_encoded = base64.urlsafe_b64encode('examplebucket'.encode()).decode().rstrip('=')
target_key_encoded = base64.urlsafe_b64encode(target_key.encode()).decode().rstrip('=')
process = f"{animation_style}|sys/saveas,b_{bucket_name_encoded},o_{target_key_encoded}/notify,topic_QXVkaW9Db252ZXJ0"
try:
# Execute the asynchronous processing task.
result = bucket.async_process_object(source_key, process)
print(f"EventId: {result.event_id}")
print(f"RequestId: {result.request_id}")
print(f"TaskId: {result.task_id}")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()Go
Go SDK 3.0.2 or later is required.
package main
import (
"encoding/base64"
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"log"
)
func main() {
// Obtain temporary access credentials from environment variables. Before you run this 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. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify the endpoint based on your actual region.
// Set yourRegion to the Alibaba Cloud region ID. Example: cn-hangzhou.
client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the bucket name. Example: examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the source video file.
sourceKey := "src.mp4"
// Specify the name of the output sprite file.
targetKey := "example.jpg"
// Configure the parameters for generating a sprite from a video.
animationStyle := "video/sprite,f_jpg,sw_100,sh_100,inter_10000,tw_10,th_10,pad_0,margin_0"
// Create a processing instruction that includes the storage path and the Base64-encoded bucket name and object name.
bucketNameEncoded := base64.URLEncoding.EncodeToString([]byte(bucketName))
targetKeyEncoded := base64.URLEncoding.EncodeToString([]byte(targetKey))
process := fmt.Sprintf("%s|sys/saveas,b_%v,o_%v/notify,topic_QXVkaW9Db252ZXJ0", animationStyle, bucketNameEncoded, targetKeyEncoded)
// Execute the asynchronous processing task.
result, err := bucket.AsyncProcessObject(sourceKey, process)
if err != nil {
log.Fatalf("Failed to async process object: %s", err)
}
fmt.Printf("EventId: %s\n", result.EventId)
fmt.Printf("RequestId: %s\n", result.RequestId)
fmt.Printf("TaskId: %s\n", result.TaskId)
}