視頻截雪碧圖(CSS Sprite或CSS Sprites)主要用於網站效能最佳化和前端開發。雪碧圖是將多個小表徵圖拼接成一張大圖,通過CSS背景定位技術減少HTTP請求,提升網頁載入速度和使用者體驗。您可以通過視頻截雪碧圖功能提取視訊框架並拼接為雪碧圖。本文介紹視頻截雪碧圖功能參數及樣本。
注意事項
視頻截雪碧圖僅支援非同步處理(x-oss-async-process處理方式)。
視頻截雪碧圖可能因視頻時間戳記或碼流損壞而失敗或數量不正確。
使用前需要先綁定IMM Project。關於控制台和API如何綁定,請參見快速入門和AttachOSSBucket - 綁定Object Storage Service桶。
不支援匿名訪問。
必須擁有IMM處理所需的相關許可權。更多資訊,請參見許可權。
參數說明
操作名稱:video/sprite
具體參數如下表所示。
參數 | 類型 | 是否必須 | 描述 |
ss | int | 否 | 視頻截雪碧圖的起始時間,單位為毫秒。取值:
|
f | string | 是 | 雪碧圖輸出格式,取值:
說明 最大支援的解析度為16384px x 16384px。 |
m | string | 否 | 雪碧圖子圖截幀模式,預設為inter,取值:
|
thr | int | 否 | 雪碧圖子圖 dhash 模式截幀閾值,閾值越大截幀數量越少,取值範圍為[0,100],預設值為 0。 說明 僅在使用 dhash 模式時有效。 dhash 模式對閾值較為敏感,推薦該參數設定不大於 25,並根據具體情境調整。 |
num | int | 否 | 雪碧圖子圖截幀數量,預設為0,表示不限制截幀數量。預設值對於不同截幀模式的物理意義如下:
重要 受視頻長度與截幀參數影響,實際截幀數量可能會小於設定的參數值。 |
inter | int | 否 | 雪碧圖子圖截幀間隔,單位為毫秒,預設為0,表示截取所有視訊框架。 說明 當該參數小於源視訊框架間隔(幀率倒數)時,會按源視訊框架間隔進行截幀。 |
sw | int | 否 | 雪碧圖子圖的寬度,單位為px,取值範圍為[32,4096],預設與源視頻寬度相同。 |
sh | int | 否 | 雪碧圖子圖的高度,單位為px,取值範圍為[32,4096],預設與源視頻高度相同。 |
psw | int | 否 | 雪碧圖子圖寬度與原始視頻寬度的百分比,取值範圍為(0,200],預設值為100。 說明 當sw與psw同時設定時,psw無效。 |
psh | int | 否 | 雪碧圖子圖高度與原始視頻高度的百分比,取值範圍為(0,200],預設值為100。 說明 當sh與psh同時設定時,psh無效。 |
scaletype | string | 否 | 縮放方式。取值:
|
tw | int | 否 | 雪碧圖每行包含的子圖數量,預設值為6,取值範圍為[1, 100]。 |
th | int | 否 | 雪碧圖每列包含的子圖數量,預設值為6,取值範圍為[1, 100]。 |
pad | int | 否 | 雪碧圖子圖間的間隔,單位px,預設值為2,取值範圍為[0, 100]。 |
margin | int | 否 | 雪碧圖邊緣間隔,單位px,預設值為2,取值範圍為[0, 100]。 |
使用REST API
在填寫視頻截雪碧圖輸出檔案儲存路徑時,若未指定尾碼名(例如“.jpg”),系統將自動添加序號(例如“_0_1.jpg”)。如果已指定尾碼名,則系統僅會保留最後一張截圖,因此不建議使用此方式。如需自訂序號,可以通過ApsaraVideo for Media Processing相關變數進行設定。
以每2秒截1幀的形式對整段視頻產生雪碧圖
以每2秒截1幀的形式對整段視頻產生雪碧圖,每張雪碧圖子圖排布為3x3,子圖解析度為200x150。
雪碧圖資訊
源檔案
視頻名稱:example.mkv
訊息通知
訊息通知MNS主題:example-mns-topic
輸出配置
截幀資訊
雪碧圖格式:jpg
雪碧圖子圖截幀時間間隔:2s
雪碧圖子圖排布格式:3x3
雪碧圖子圖解析度:200x150
雪碧圖子圖縮放方式:縮放並裁剪
雪碧圖子圖間隔:0
雪碧圖子圖與雪碧圖邊緣間隔:0
檔案儲存體路徑
jpg檔案:oss://outbucket/outobjprefix-%d.jpg
處理樣本
// 對檔案example.mkv進行視頻截雪碧圖。
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_ZXhhbXBsZS1tbnMtdG9waWMK根據數量均勻截幀對視頻產生雪碧圖
產生一張10行10列的雪碧圖,子圖內容均勻覆蓋整段視頻,簡化前端代碼邏輯。
雪碧圖資訊
源檔案
視頻名稱:example.mkv
訊息通知
訊息通知MNS主題:example-mns-topic
輸出配置
截幀資訊
雪碧圖格式:jpg
雪碧圖子圖截幀模式:avg
雪碧圖子圖排布格式:10x10
雪碧圖子圖解析度:源視頻1/10
雪碧圖子圖縮放方式:等比縮放
雪碧圖子圖間隔:4
雪碧圖子圖與雪碧圖邊緣間隔:5
檔案儲存體路徑
jpg檔案:oss://outbucket/outobjprefix-%d.jpg
處理樣本
// 對檔案example.mkv進行視頻截雪碧圖。
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_ZXhhbXBsZS1tbnMtdG9waWMK使用SDK
僅支援使用Java、Python、Go SDK通過非同步處理的方式完成視頻截雪碧圖,具體請參見安裝SDK。
Java
要求使用3.17.4及以上版本的Java SDK。
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 {
// yourEndpoint填寫Bucket所在地區對應的Endpoint。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 填寫Endpoint對應的Region資訊,例如cn-hangzhou。
String region = "cn-hangzhou";
// 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 指定Bucket名稱。
String bucketName = "examplebucket";
// 指定雪碧圖的檔案名稱。
String targetKey = "example.jpg";
// 指定原視頻檔案名稱。
String sourceKey = "src.mp4";
// 建立OSSClient執行個體。
// 當OSSClient執行個體不再使用時,調用shutdown方法以釋放資源。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 構建視頻轉雪碧圖參數。
String style = String.format("video/sprite,f_jpg,sw_100,sh_100,inter_10000,tw_10,th_10,pad_0,margin_0");
// 構建非同步處理指示。
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);
// 建立AsyncProcessObjectRequest對象。
AsyncProcessObjectRequest request = new AsyncProcessObjectRequest(bucketName, sourceKey, process);
// 執行非同步處理任務。
AsyncProcessObjectResult response = ossClient.asyncProcessObject(request);
System.out.println("EventId: " + response.getEventId());
System.out.println("RequestId: " + response.getRequestId());
System.out.println("TaskId: " + response.getTaskId());
} finally {
// 關閉OSSClient。
ossClient.shutdown();
}
}
}Python
要求使用Python SDK 2.18.4及以上版本。
# -*- coding: utf-8 -*-
import base64
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# 從環境變數中擷取臨時訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# 填寫Bucket所在地區對應的Endpoint。以華東1(杭州)為例,Endpoint填寫為https://oss-cn-hangzhou.aliyuncs.com。
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# 填寫Endpoint對應的Region資訊,例如cn-hangzhou。
region = 'cn-hangzhou'
# 填寫Bucket名稱。
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)
# 指定原視頻檔案名稱。
source_key = 'src.mp4'
# 指定雪碧圖檔案名稱。
target_key = 'example.jpg'
# 構建視頻轉雪碧圖參數。
animation_style = 'video/sprite,f_jpg,sw_100,sh_100,inter_10000,tw_10,th_10,pad_0,margin_0'
# 構建處理指示,包括儲存路徑和Base64編碼的Bucket名和目標檔案名。
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:
# 執行非同步處理任務。
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及以上版本。
package main
import (
"encoding/base64"
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"log"
)
func main() {
// 從環境變數中擷取臨時訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// 建立OSSClient執行個體。
// yourEndpoint填寫Bucket對應的Endpoint,以華東1(杭州)為例,填寫為https://oss-cn-hangzhou.aliyuncs.com。其他Region請按實際情況填寫。
// yourRegion指定阿里雲通用Region ID,例如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)
}
// 指定Bucket名稱,例如examplebucket。
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// 指定原視頻檔案名稱。
sourceKey := "src.mp4"
// 指定輸出的雪碧圖檔案名稱。
targetKey := "example.jpg"
// 構建視頻轉雪碧圖參數。
animationStyle := "video/sprite,f_jpg,sw_100,sh_100,inter_10000,tw_10,th_10,pad_0,margin_0"
// 構建處理指示,包括儲存路徑和Base64編碼的Bucket名和目標檔案名。
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)
// 執行非同步處理任務。
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)
}