Python如何快速建立 GIF 动图?图片神器Pillow帮你解决

前言网络

本文的文字及图片来源于网络,仅供学习、交流使用,不具备任何商业用途,版权归原做者全部,若有问题请及时联系咱们以做处理。app

做者:EarlGrey函数

 

 

什么是 GIF 图?

GIF(“图形交换格式”)是一种位图图像格式,于1987年开发。oop

GIF基本上是一系列具备不一样设置的图像,例如:学习

  • 循环播放
  • 每帧的持续时间(图片)
  • 其余…

GIF 也能够是静态图像。code

 

 

Pillow

Pillow 是 Python 图形处理库 PIL 的一个分支,引入了许多更改和加强功能,以使API易于使用或处理更多图像格式和要求。支持打开、处理和保存多种不一样格式的图片文件。orm

利用 Python 生成 GIF

安装 Pillow

第一步,咱们须要先安装 Pillow:blog

pip install Pillow

生成 GIF

咱们生成一张红球往下坠落的 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

​​​​​​​解释下上面的代码:

  1. 初始化一个空列表 frames ,以及 0点坐标 x 和 y
  2. 用一个运行十次的 for 循环,每次建立一张 400x400 大小的图片,图片中红球的位置不一样
  3. 更改红球的坐标,让红球沿着对角线往下坠
  4. 设置参数 format='GIF', append_images=frames[1:],保存 GIF 图片
  • 每帧图片播放100毫秒( duration=100
  • GIF图片一直重复循环( loop=0,若是设置为 1,则循环1次,设置为2则循环2次,以此类推)

 

最终生成的 GIF 图大概是下面这样的:

相关文章
相关标签/搜索