All Products
Search
Document Center

Object Storage Service:Video-to-animated-image conversion

Last Updated:Jul 08, 2025

Video-to-animated-image conversion is a media processing technique that converts videos into animated images in GIF or WebP format.

Feature introduction

Video-to-animated-image conversion transforms video files into animated image formats, such as GIF or WebP, to facilitate convenient sharing and embedding on websites and social media platforms.

zhuandongtu

Scenarios

  • Social media sharing: Animated images allow users to conveniently share video clips on social platforms to express emotions, humorous moments, or important information.

  • Online stickers: Converting videos to animated images can be used to create fun or humorous stickers, enhancing the enjoyment of online communication.

  • Tutorials and demonstrations: In teaching and demonstrations, animated images can be used to showcase software operations or step-by-step guides to help the audience quickly understand complex concepts and procedures.

  • Live streaming and event playback: Animated images can be used during competitions, events, or live broadcasts to quickly clip and share highlights, thereby enhancing audience engagement.

How to use

Prerequisites

Video-to-animated-image conversion

You can use OSS SDK for Java, Python, or Go to convert a video to an animated image.

Java

OSS SDK for Java V3.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 {
        // Set yourEndpoint to the endpoint of the region in which the bucket is located.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region that corresponds to the endpoint. For 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 name of the bucket.
        String bucketName = "examplebucket";
        // Specify the name of the destination animated GIF file.
        String targetKey = "dest.gif";
        // Specify the name of the source video file.
        String sourceKey = "src.mp4";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer in use, 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 {
            // Create a style string that contains the parameters for the video-to-animated-image conversion.
            String style = String.format("video/animation,f_gif,w_100,h_100,inter_1000");
            // 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 instance.
            ossClient.shutdown();
        }
    }
}

Python

OSS SDK for Python V2.18.4 or later is required.

# -*- coding: utf-8 -*-
import base64
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Obtain the temporary access credentials 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.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    # 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.
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    # Specify the ID of the Alibaba Cloud region in which the bucket is located. Example: cn-hangzhou.
    region = 'cn-hangzhou'

    # Specify the name of the bucket. Example: examplebucket.
    bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)

    # Specify the name of the video.
    source_key = 'src.mp4'

    # Specify the name of the animated GIF image.
    target_key = 'example.gif'

    # Specify the parameters for converting the video to GIF animation, including the GIF width, height, and time interval for capturing frames.
    animation_style = 'video/animation,f_gif,w_100,h_100,inter_1000'

    # Create a processing instruction, in which the name of the bucket and the name of the output object are Base64-encoded.
    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:
        # Run 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

OSS SDK for Go V3.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 the temporary access credentials 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.
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
    }
    // Create an OSSClient instance.
    // 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. Specify your actual endpoint.
    // Specify the ID of the Alibaba Cloud region in which the bucket is located. 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 name of the bucket. Example: examplebucket.
    bucketName := "examplebucket"

    bucket, err := client.Bucket(bucketName)
    if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
    }

    // Specify the name of the video.
    sourceKey := "src.mp4"
    // Specify the name of the animated GIF image.
    targetKey := "destexample.gif"

    // Specify the parameters for converting the video to GIF animation, including the GIF width, height, and time interval for capturing frames.
    animationStyle := "video/animation,f_gif,w_100,h_100,inter_1000"

    // Create a processing instruction, in which the name of the bucket and the name of the output object are Base64-encoded.
    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)

    // Run 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)
}

Parameters

Action: video/animation

The following table describes the parameters.

Parameter

Type

Required

Description

ss

int

No

The point in time of the video at which the video-to-animated-image conversion begins. Unit: milliseconds. Valid values:

  • 0 (default): The conversion begins at the start position of the video.

  • Greater than 0: Starts from the ss millisecond.

f

string

Yes

The format of the animated image. Valid values:

  • gif

  • webp

num

int

No

The number of frames that the animated image contains. The number of frames in the animated image is not limited by default, meaning that frame extraction lasts until the end of the video.

Important

If the video is not long enough to extract the specified number of frames, the actual number of extracted frames is less than the specified number of frames.

inter

int

No

The time interval at which frames are extracted from the video. Unit: milliseconds. By default, all frames are extracted from the video.

Note

If the value of this parameter is less than the frame interval of the video (the reciprocal of the frame rate), frames are extracted from the video based on the frame interval of the video.

fps

float

No

The frame rate of the animated image. The default value is the reciprocal of inter. Valid values: 0 to 240.

Note

This parameter determines the playback speed of the animated image. If the default value is used, the playback speed of the animated image matches the playback speed of the video. A value greater than the default value results in faster playback, whereas a value lower than the default value slows down the playback.

w

int

No

The width of the animated image. Unit: pixel. Valid values: 32 to 4096. By default, the width of the animated image equals to the width of the video.

h

int

No

The height of the animated image. Unit: pixel. Valid values: 32 to 4096. By default, the height of the animated image equals to the height of the video.

scaletype

string

No

The resizing mode. Valid values:

  • crop: resizes and crops the frame.

  • stretch (default): stretches the frame to fill the entire space.

  • fill: resizes the frame and keeps the black border.

  • fit: resizes the frame proportionally and removes the black border.

Note

When you convert a video to an animated image, the sys/saveas and notify parameters are used. For more information, see Save as and Message notification.

Related API

Extract frames from a video at intervals of 1 second to create an animated image

Source video file: example.mkv

Processing parameters:

  • Conversion format: gif (f_gif)

  • Output image resolution: 100 px × 100 px (w_100,h_100)

  • Frame extraction interval: 1 second (inter_1000)

Storage path: oss://outbucket/outobjprefix.{autoext}

  • Bucket: outbucket (Base64-encoded: b_b3V0YnVja2V0)

  • Object: outobjprefix.{autoext} (Base64-encoded: o_b3V0b2JqcHJlZml4LnthdXRvZXh0fQ)

Notification parameters:

  • Notification method: Send an MNS message

  • Notification topic: AudioConvert (Base64 encoded: topic_QXVkaW9Db252ZXJ0)

Sample request

// Create an animated image from the video example.mkv.
POST /example.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/animation,f_gif,w_100,h_100,inter_1000|sys/saveas,b_b3V0YnVja2V0,o_b3V0b2JqcHJlZml4LnthdXRvZXh0fQ/notify,topic_QXVkaW9Db252ZXJ0

Extract frames at intervals of 0.5 seconds from the fifth second to create an animated image

Source video file: example.mkv

Processing parameters:

  • Format: webp (f_webp)

  • Resolution of the output image: one-fourth of the width and height of the source video (pw_25, ph_25)

  • Frame extraction interval: 0.5s (inter_500)

Storage path: oss://outbucket/outobjprefix.{autoext}

  • Bucket: outbucket (Base64-encoded: b_b3V0YnVja2V0)

  • Object: outobjprefix.{autoext} (Base64-encoded: o_b3V0b2JqcHJlZml4LnthdXRvZXh0fQ)

Notification parameters:

  • Notification method: Send an MNS message

  • Notification subject: AudioConvert (Base64-encoded: topic_QXVkaW9Db252ZXJ0)

Sample request

// Create an animated image from the video example.mkv.
POST /example.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/animation,ss_5000,f_webp,pw_25,ph_25,fps_25,inter_500|sys/saveas,b_b3V0YnVja2V0,o_b3V0b2JqcHJlZml4LnthdXRvZXh0fQ/notify,topic_QXVkaW9Db252ZXJ0

Billing

During the video-to-animated-image conversion process, because the IMM service is called, the following billing items are generated on both OSS and IMM sides:

  • OSS side: For detailed pricing, see OSS Pricing

    API

    Billing item

    Description

    GetObject

    GET requests

    You are charged request fees based on the number of successful requests.

    Outbound traffic over Internet

    If you call the GetObject operation by using a public endpoint, such as oss-cn-hangzhou.aliyuncs.com, or an acceleration endpoint, such as oss-accelerate.aliyuncs.com, you are charged fees for outbound traffic over the Internet based on the data size.

    Data retrieval of IA objects

    If IA objects are retrieved, you are charged IA data retrieval fees based on the size of retrieved IA data.

    Archive Direct Read Retrieval Capacity

    If Archive objects in a bucket for which real-time access is enabled are retrieved, you are charged Archive data retrieval fees based on the size of retrieved Archive objects.

    Transfer acceleration

    If you enable transfer acceleration and use an acceleration endpoint to access your bucket, you are charged transfer acceleration fees based on the data size.

    PutObject

    PUT requests

    You are charged request fees based on the number of successful requests.

    Storage fees

    You are charged storage fees based on the storage class, size, and storage duration of the object.

    HeadObject

    GET requests

    You are charged request fees based on the number of successful requests.

  • IMM side: For detailed pricing, see IMM billing items

    Important

    Starting from 11:00 on July 28, 2025 (UTC+8), the IMM video-to-animated-image conversion service will be upgraded from a free model to a paid model. The specific billing item is MediaAnimation. For more information, see IMM billing adjustment announcement.

    API

    Billing item

    Description

    CreateMediaConvertTask

    MediaAnimation

    The video-to-animated-image conversion fee is calculated based on the number of frames in the output animated image

Usage notes

  • Video-to-animated-image conversion supports only asynchronous processing (x-oss-async-process).

  • Anonymous access will be denied.