【问题标题】:How to save an animated GIF to a variable using Pillow如何使用 Pillow 将动画 GIF 保存到变量中
【发布时间】:2018-12-04 08:52:12
【问题描述】:

我从here 发现我可以使用 Pillow 创建和保存动画 GIF。但是,the save method 似乎没有返回任何值。

我可以将 GIF 保存到一个文件中,然后使用 Image.open 打开该文件,但这似乎没有必要,因为我真的不想保存 GIF。

如何将 GIF 保存到变量而不是文件? 也就是说,我希望能够执行some_variable.show() 并显示 GIF,而不必将 GIF 保存到我的计算机上。

【问题讨论】:

    标签: variables save gif pillow


    【解决方案1】:

    为避免写入任何文件,您只需将图像保存到 BytesIO 对象即可。例如:

    #!/usr/bin/env python
    
    from __future__ import division
    from PIL import Image
    from PIL import ImageDraw
    from io import BytesIO
    
    N = 25          # number of frames
    
    # Create individual frames
    frames = []
    for n in range(N):
        frame = Image.new("RGB", (200, 150), (25, 25, 255*(N-n)//N))
        draw = ImageDraw.Draw(frame)
        x, y = frame.size[0]*n/N, frame.size[1]*n/N
        draw.ellipse((x, y, x+40, y+40), 'yellow')
        # Saving/opening is needed for better compression and quality
        fobj = BytesIO()
        frame.save(fobj, 'GIF')
        frame = Image.open(fobj)
        frames.append(frame)
    
    # Save the frames as animated GIF to BytesIO
    animated_gif = BytesIO()
    frames[0].save(animated_gif,
                   format='GIF',
                   save_all=True,
                   append_images=frames[1:],      # Pillow >= 3.4.0
                   delay=0.1,
                   loop=0)
    animated_gif.seek(0,2)
    print ('GIF image size = ', animated_gif.tell())
    
    # Optional: display image
    #animated_gif.seek(0)
    #ani = Image.open(animated_gif)
    #ani.show()
    
    # Optional: write contents to file
    animated_gif.seek(0)
    open('animated.gif', 'wb').write(animated_gif.read())
    

    最后,变量animated_gif包含下图的内容:

    但是,在 Python 中显示动画 GIF 并不是很可靠。上面代码中的ani.show() 仅在我的机器上显示第一帧。

    【讨论】:

    • 您仍在保存它,然后将其重新加载到变量animated_gif 中。如何在不需要 frames[0].save 行的情况下让 animated_gif 成为动画?
    • @ProQ,就是这样。它可能看起来不太理想或奇怪,但这就是 PIL/Pillow 的编写方式。此外,您的问题是:“如何将 GIF 保存到变量而不是文件?” - 这就是答案。
    • 此外,还必须保存/加载每一帧以提高生成动画的质量和大小。这就是 PIL 现在的工作方式(使用 Pillow 5.1.0 测试)。
    猜你喜欢
    • 2014-09-01
    • 2015-01-30
    • 2018-11-12
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 2021-06-24
    相关资源
    最近更新 更多