前言网络
本文的文字及图片来源于网络,仅供学习、交流使用,不具备任何商业用途,版权归原做者全部,若有问题请及时联系咱们以做处理。app
做者:EarlGrey函数
GIF(“图形交换格式”)是一种位图图像格式,于1987年开发。oop
GIF基本上是一系列具备不一样设置的图像,例如:学习
GIF 也能够是静态图像。code
Pillow 是 Python 图形处理库 PIL 的一个分支,引入了许多更改和加强功能,以使API易于使用或处理更多图像格式和要求。支持打开、处理和保存多种不一样格式的图片文件。orm
第一步,咱们须要先安装 Pillow:blog
pip install Pillow
咱们生成一张红球往下坠落的 GIF 动图,做为文章示例。图片
首先,编写一个函数,利用 Pillow 在一张图片上画一个红球。ip
from PIL import Image, ImageDraw
def create_image_with_ball(width, height, ball_x, ball_y, ball_size):
img = Image.new('RGB', (width, height), (255, 255, 255))
draw = ImageDraw.Draw(img)
# draw.ellipse takes a 4-tuple (x0, y0, x1, y1) where (x0, y0) is the top-left bound of the box
# and (x1, y1) is the lower-right bound of the box.
draw.ellipse((ball_x, ball_y, ball_x + ball_size, ball_y + ball_size), fill='red')
return img
上述代码中,咱们使用 Image.new
建立了一张 RGB 图片,并设置背景为白色,指定了图片大小。
接着,经过 ImageDraw
在图片中的指定参数位置,画了一个红色的圆圈。因此,咱们要作的就是建立多张图片,不断让红球往下坠。
# Create the frames
frames = []
x, y = 0, 0
for i in range(10):
new_frame = create_image_with_ball(400, 400, x, y, 40)
frames.append(new_frame)
x += 40
y += 40
# Save into a GIF file that loops forever
frames[0].save('moving_ball.gif', format='GIF', append_images=frames[1:], save_all=True, duration=100, loop
解释下上面的代码:
frames
,以及 0点坐标 x
和 y
format='GIF'
, append_images=frames[1:]
,保存 GIF 图片duration=100
)loop=0
,若是设置为 1,则循环1次,设置为2则循环2次,以此类推)
最终生成的 GIF 图大概是下面这样的: