Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I load an animated GIF and get all of the individual frames in Pygame?

First of all, sorry if this is a duplicate. The answers that I found either seemed irrelevant but perhaps I'm searching with the wrong keywords. What I'd like to do is to take an animated GIF and split it up into a list of frames. Basically, something like this:

frames = []
for frame in split_animated_gif("some_animated_gif.gif"):
    frames.append(frame)

where split_animated_gif returns a list of surfaces, each of which is a frame of the GIF, in order. Thank you for your help.

EDIT: After some more snooping, I found a piece of code that successfully displayed an animated GIF in pygame for me. It can be found at https://github.com/piantado/kelpy/blob/master/kelpy/GIFImage.py. Your help was much appreciated, though.

like image 368
user4594444 Avatar asked Apr 10 '15 22:04

user4594444


2 Answers

Pygame itself does not support animated gifs, which is stated in the documentation. So you'll have to

1) use some other piece of code / library to split the gif when you're loading your sprites or images. Those you would find just by googling for "python split gif" or something. E.g. Python: Converting GIF frames to PNG

2) if you created the gif yourself, just export your sprites again frame by frame

Either way, you'll have to do the animating part by hand. Which for you'll find plenty of tutorials by googling "pygame animation". E.g. Animated sprite from few images

like image 102
Roope Avatar answered Oct 18 '22 05:10

Roope


This code does it using PIL / pillow library.

from PIL import Image

def split_animated_gif(gif_file_path):
    ret = []
    gif = Image.open(gif_file_path)
    for frame_index in range(gif.n_frames):
        gif.seek(frame_index)
        frame_rgba = gif.convert("RGBA")
        pygame_image = pygame.image.fromstring(
            frame_rgba.tobytes(), frame_rgba.size, frame_rgba.mode
        )
        ret.append(pygame_image)
    return ret
like image 4
Anthony Hayward Avatar answered Oct 18 '22 05:10

Anthony Hayward