详解用Python pillow 创建和保存GIF动画

  • Post category:Python

下面是用Python pillow创建和保存GIF动画的详细攻略:

安装pillow库

使用Python pillow创建和保存GIF动画,需要先安装pillow库。你可以使用以下命令安装:

pip install pillow

创建GIF动画

要创建GIF动画,我们需要将一系列图片合成到一起,并将之变成GIF动画。以下是一个Python函数,该函数接受图片的路径和GIF文件的名称,并将多张图片合成为GIF动画:

from PIL import Image, ImageDraw

def create_gif(filenames, duration):
    images = []
    for filename in filenames:
        images.append(Image.open(filename))

    output_file = 'animation.gif'

    # Save the frames as an animated GIF
    images[0].save(output_file, format='GIF', save_all=True, append_images=images[1:], duration=duration, loop=0)

参数说明:

filenames: 图片路径列表

duration: GIF动画的播放速度,单位为毫秒

接下来,我们可以使用以下示例代码来调用此函数:

filenames = ['1.jpg', '2.jpg', '3.jpg']
duration = 300
create_gif(filenames, duration)

这个例子中,我们使用3个jpg文件来创建动画,每个图片之间的播放速度为300ms。

修改GIF动画

除了创建新的GIF动画,我们还可以使用Python pillow库修改现有的GIF动画。以下代码示例演示如何将一个GIF动画的帧倒序播放:

from PIL import Image

image = Image.open('animation.gif')

# Reverse the frames
frames = []
for i in range(len(image.seek(0)), 0, -1):
    image.seek(i)
    frames.append(image.copy())

# Save the frames as an animated GIF
output_file = 'reverse_animation.gif'
frames[0].save(output_file, format='GIF', save_all=True, append_images=frames[1:], duration=100, loop=0)

参数说明:

duration: GIF动画的播放速度,单位为毫秒

以上就是用Python pillow创建和保存GIF动画的完整攻略,希望能对你有帮助。