Animated GIFs?!!?! Urgent Help

Fredrik Lundh fredrik at effbot.org
Sun Nov 12 05:58:24 EST 2000


Freeserve wrote:
> I'm new to python and all this, but I am doing a really complicated project
> using this language (which I seem to like more and more each day)...
>
> Anyway, could anyone tell me if there is any simple way of reading and
> displaying an animated GIF file using PIL?

to read frames from an animated GIF file, just open it as usual,
and use seek to move to the next frame.  PIL will raise an EOF-
Error when you attempt to seek beyond the end of the file.

    im = Image.open("in.gif")
    sequence = []
    try:
        while 1:
            sequence.append(im.copy())
            im.seek(len(sequence)) # skip to next frame
    except EOFError:
        pass # we're done

(note that seek modifies the image in place; I use copy to make
sure the sequence contains the distinct frames instead of a couple
of pointers to the *same* image object, all positioned at the last
frame)

:::

to write GIF files, see the gifmaker.py sample script provided with
the PIL source distribution:

    import Image
    import gifmaker

    sequence = []

    # generate sequence
    for i in range(100):
        im = <generate image i>
        sequence.append(im)

    # write GIF animation
    fp = open("out.gif", "wb")
    gifmaker.makedelta(fp, sequence)
    fp.close()

</F>





More information about the Python-list mailing list