Find the duration of GIF image in Python

After reading this post, you will have a general idea of how you can work with gifs using PIL(Python Imaging Library). Access its metadata information and find relevant ( human-readable) results. Here is a simple program to find the duration of GIF image in Python.

Installation of the PIL module in Python 3.7

you can install PIL by typing, the following command on your terminal:
pip install pillow

Reading Image info using Pillow:

you can open any image and read its info, by simply typing this:

from PIL import Image

print(Image.open('sample.gif').info) # return dictionary object

# which can be accessed similar to any python dictionary.

Getting the Duration of the GIF

If you simply type this command, print(Image.open('sample.gif').info['duration']) you’ll get some value but that is not the actual duration of the GIF, instead, that one is the frame duration of (generally) the first frame (frame 0).

So to do this operation, you need to loop through all the frames of that .gif file and sum up the duration until no frames are left or an EOFError is generated.

So I have used this gif for my code:

Find the duration of GIF image in Python

Code for this looks like:

import os
from PIL import Image
def find_duration(img_obj):
    img_obj.seek(0)  # move to the start of the gif, frame 0
    tot_duration = 0
    # run a while loop to loop through the frames
    while True:
        try:
            frame_duration = img_obj.info['duration']  # returns current frame duration in milli sec.
            tot_duration += frame_duration
            # now move to the next frame of the gif
            img_obj.seek(img_obj.tell() + 1)  # image.tell() = current frame
        except EOFError:
            return tot_duration # this will return the tot_duration of the gif

if __name__ == '__main__':
    filepath = input('Enter the file path for the gif:')
    if os.path.exists(filepath):
        img = Image.open(filepath)
        gif_duration = find_duration(img)
        print(f'Duration of {os.path.basename(filepath)} is {gif_duration/1000} s')  # divide by 1000 to convert to seconds
    else:
        print('Invalid path entered!')

and the output for this is:

Find the duration of GIF image in Python

This is how we can find the duration of GIF image in Python.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *