Python Pillow 简明教程

Python Pillow - Creating Animated GIFs

GIF(图形交换格式)是由 CompuServe 在线服务提供商的一个团队在美国计算机科学家 Steve Wilhite 的领导下开发的位图图像格式。GIF 没有被设计成动画媒体。然而,它可以在单个文件中存储多个图像的能力使其成为表示动画序列帧的合理选择。为了支持动画演示,GIF89a 规范引入了图形控制扩展 (GCE)。此扩展允许为每个帧指定时间延迟,有效地允许从一系列图像创建视频剪辑。

在动画 GIF 中,每个帧都由自己的 GCE 引入,指定在绘制帧后应发生的延迟时间。此外,在文件开头定义的全局信息作为所有帧的默认设置应用,简化了动画设置和行为的管理。

Python 的 Pillow 库可以读取 GIF87a 和 GIF89a 格式的 GIF 文件。默认情况下,它以 GIF87a 格式写入 GIF 文件,除非使用了 GIF89a 特性或输入文件已采用 GIF89a 格式。保存的文件使用 LZW 编码。

Creating Animated GIFs with Python Pillow

可以使用 Pillow 的 Image.save() 函数创建动画 GIF。以下是调用 save() 函数以保存 GIF 文件时的语法和可用选项−

Syntax:

Image.save(out, save_all=True, append_images=[im1, im2, ...])

Options:

  1. save_all − 如果设置为 true,则它将保存图像的所有帧。否则,它只保存多帧图像的第一帧。

  2. append_images − 此选项允许附加图像列表作为附加帧。列表中的图像可以是单帧或多帧图像。此特性受 GIF、PDF、PNG、TIFF 和 WebP 格式以及 ICO 和 ICNS 格式支持。在提供了相关大小的图像时,它们将被使用,而不是缩小主图像。

  3. include_color_table − 确定是否包含本地颜色表。

  4. interlace − 指定图像是否交错。默认情况下,启用交错,除非图像的宽度或高度小于 16 个像素。

  5. disposal − 指示在显示后如何处理图形。它可以设置为 0(未指定释放)、1(不释放)、2(还原为背景颜色)或 3(还原为前一内容)等值。您可以传递单个整数以进行恒定释放,或传递列表/元组以针对每个帧分别设置释放。

  6. palette − 此选项允许您为保存的图像使用一个特定的调色板。调色板应作为包含 RGBRGB…​ 形式的调色板条目的字节或字节数组对象提供。它不得超过 768 个字节。或者,您可以将调色板传递为 PIL.ImagePalette.ImagePalette 对象。

  7. optimize - 如果设为 true,它将尝试通过消除未使用颜色压缩调色盒。当调色盒可以压缩为 2 个元素的紧邻较小幂时,此优化程序非常有用。

  8. 可以提供诸如透明度、时间、循环和注释等附加选项来控制动画 GIF 的特定方面。

Example

以下示例演示了如何通过生成具有不同颜色的各个帧并保存它们来创建 GIF 动画。

import numpy as np
from PIL import Image

# Function to create a new image with a specified width, height, and color
def create_image(width, height, color):
   return Image.new("RGBA", (width, height), color)

# Set the width and height of the images
width, height = 300, 300

# Define the colors for the images
colors = [(64, 64, 3), (255, 0, 0), (255, 255, 0), (255, 255, 255), (164, 0, 3)]

# Create a list of images using a list comprehension
images = [create_image(width, height, color) for color in colors]

# Save the images as a GIF with specified parameters
images[0].save("Output.gif", save_all=True, append_images=images[1:], duration=1000/2, loop=0)
The animated GIFs file is saved successfully...

你可以下方目录中看到已保存的动画 GIF −

output

Example

以下示例采用现有图像文件列表,通过按顺序保存这些图像来创建动画 GIF。

from PIL import Image

# List of file paths for existing images
image_paths = ['Images/book_1.jpg', 'Images/book_2.jpg', 'Images/book_3.jpg', 'Images/book_4.jpg']

# Create a list of image objects from the provided file paths
image_list = [Image.open(path) for path in image_paths]

# Save the first image as an animated GIF
output_path = \Book_Animation.gif'

image_list[0].save(
   output_path,
   save_all=True,
   append_images=image_list[1:],  # Append the remaining images
   duration=1000,  # Frame duration in milliseconds
   loop=0
)

print('The animated GIF file has been created and saved successfully...')
The animated GIF file has been created and saved successfully...

以下图像展示了在你工作目录保存的动画 GIF −

book animation

Example

此示例通过重复现有 GIF 文件的最后一帧几次来修改该文件,然后将其另存为一个新 GIF 文件。在该示例中,我们将使用 ImageSequence 模块来迭代输入 GIF 文件中的各个帧。

from PIL import Image, ImageSequence

# Open the existing GIF file
input_image = Image.open("Book_Animation.gif")

# Create an empty list to store the frames of the GIF
frames = []

# Iterate over the frames of the GIF and append them to the frames list
for frame in ImageSequence.Iterator(input_image):
   frames.append(frame)

# Duplicate the last frame three times to extend the animation
for i in range(3):
   frames.append(frames[-1])

# Save the frames as a new GIF file ("newGif.gif"):
output_path = "newGif.gif"
frames[0].save(
   output_path,
   save_all=True,
   append_images=frames[1:],
   optimize=False,
   duration=40,  # Set the frame duration to 40 milliseconds
   loop=0
)

以下图像展示了在你工作目录保存的动画 GIF −

book animation