zoukankan      html  css  js  c++  java
  • Python如何快速创建 GIF 动图?图片神器Pillow帮你解决

    前言

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

    作者:EarlGrey

     

    什么是 GIF 图?

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

    GIF基本上是一系列具有不同设置的图像,例如:

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

    GIF 也可以是静态图像。

     

     

    Pillow

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

    利用 Python 生成 GIF

    安装 Pillow

    第一步,我们需要先安装 Pillow:

    pip install Pillow

    生成 GIF

    我们生成一张红球往下坠落的 GIF 动图,作为文章示例。

    首先,编写一个函数,利用 Pillow 在一张图片上画一个红球。

    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 图大概是下面这样的:

  • 相关阅读:
    TRECT的使用
    杂记
    Delphi中停靠技术的实现
    高级停靠(Dock)技术的实现
    高级停靠(Dock)技术的实现
    vue组件内的元素转移到指定位置
    mintui loadmore组件使用+代码优化
    vue项目进行nuxt改造
    blob与arraybuffer
    vue项目首屏加载过久处理笔记
  • 原文地址:https://www.cnblogs.com/zwhy8/p/13323293.html
Copyright © 2011-2022 走看看