Python图像处理之pillow-GIF图

如何使用Python显示并播放GIF图呢?

上代码:

# _*_ coding:utf-8 _*_

import pyglet
__author__ = admin


    python显示GIF图


#   如果需要展示的GIF图未在工作目录下,这里需要先指明目标文件夹
pyglet.resource.path = [rC:UsersadminDesktop]
#   animation中需要填入的是目标文件的文件名
animation = pyglet.resource.animation(scream.gif)
#   获取GIF图的实例
sprite = pyglet.sprite.Sprite(animation)
#   设定窗口的大小
win = pyglet.window.Window(width=sprite.width, height=sprite.height)

@win.event
def on_draw():
    win.clear()
    sprite.draw()

pyglet.app.run()

需要注意的是:

①如果目标文件不在你的工作目录下,这是后你需要先指明目标文件的文件夹:

pyglet.resource.path = [rC:UsersadminDesktop]

而animation方法中需要加入的是目标文件的文件名

animation = pyglet.resource.animation(scream.gif)

②Sprite(not雪碧的意思!)解释如下:

sprite是屏幕上显示的图像的一个实例。多个sprite可以在屏幕上的不同位置显示相同的图像。sprite也可以放大或缩小,以任意角度旋转,并以不透明度进行绘制。通常是先加载一个动态图,再为该图创建一个sprite,然后在窗口的绘制事件处理程序中绘制sprite。

补充一点就是pyglet的安装:pip install pyglet

如何实现GIF的倒序播放呢?

上原图:

上代码:

#   _*_ coding:utf-8 _*_

from PIL import Image, ImageSequence

__author__ = admin

im = Image.open(rC:UsersadminDesktopaction.gif)
#   初始化列表
sequence = []
for f in ImageSequence.Iterator(im):
    #   获取图像序列病存储
    sequence.append(f.copy())
#   将图像序列逆转
sequence.reverse()
sequence[0].save(rC:UsersadminDesktopout.gif, save_all=True, append_images=sequence[1:])

那么我们在获取到图像序列后,并将其随机打乱会产生什么化学反应呢?

#   _*_ coding:utf-8 _*_
import random
from PIL import Image, ImageSequence

__author__ = admin

im = Image.open(rC:UsersadminDesktopaction.gif)
#   初始化列表
sequence = []
for f in ImageSequence.Iterator(im):
    #   获取图像序列病存储
    sequence.append(f.copy())
#   随机打乱图像序列
random.shuffle(sequence)
#   将图像序列逆转
# sequence.reverse()
sequence[0].save(rC:UsersadminDesktopout.gif, save_all=True, append_images=sequence[1:])
经验分享 程序员 微信小程序 职场和发展