使用Python生成一个摸摸头动图
python生成摸头GIF
本篇教程演示了如何使用python的PIL库生成GIF图片
源代码已经张贴在文章中,可以自己使用。
[En]
The source code has been posted in the article and can be used by yourself.
效果演示
运行代码将允许您选择要制作的图片
[En]
Running the code will let you choose the picture you want to make
运行完成后,会在同路径下生成dem.gif
原理
- 本源码主要用到PIL库的Image模块
- 使用Image模块的相关方法处理每一帧的图片
- 存储到GIF列表并生成GIF
- 需要先调试好参数
源码
完整的代码和材料打包在附件中,并在文章末尾下载。
[En]
The complete code and materials are packaged in the attachment and downloaded at the end of the article.
环境:python3.7
'''
不需要图形界面的
记得自己删除tk模块相关
并添加图像接收入口
rua("图像路径").add_gif()
'''
from tkinter import filedialog
from PIL import Image,ImageDraw
import os,tkinter
class rua():
def __init__(self,img_file):
# 载入图片
self.author = Image.open(img_file)
def add_png(self,png_d):
# 根据参数重置图片大小
author = self.author.resize((png_d[0],png_d[1] - png_d[2]))
# 载入素材
rua_p1 = Image.open(png_d[3])
# 创建背景模板
rua_png1 = Image.new('RGBA',(110,110),(255,255,255,255))
# 使用预定义的参数:jd,合成一帧的样例
rua_png1.paste(author,(110 - png_d[0],110 - png_d[1] + png_d[2]),author)
rua_png1.paste(rua_p1,(0,110 - png_d[1] - png_d[2]),rua_p1)
return rua_png1
def add_gif(self):
# 获取绝对路径
png_dir = os.getcwd() + '\\data\\'
# 获取素材列表
pst = os.listdir(png_dir)
for i in range(len(pst)):
pst[i] = png_dir + pst[i]
# 预调试好的参数,传入素材列表
jd = [[90,90,5,pst[0]],
[90,87,5,pst[2]],
[90,84,10,pst[3]],
[90,81,8,pst[4]],
[90,78,5,pst[5]],
[90,75,5,pst[6]],
[90,72,8,pst[7]],
[90,74,8,pst[8]],
[90,77,9,pst[9]],
[90,80,8,pst[1]]]
# 重置要生成的图片大小
self.author = self.author.resize((90,90))
# 绘制模板
alpha_layer = Image.new('L', (90, 90), 0)
draw = ImageDraw.Draw(alpha_layer)
draw.ellipse((0,0,90,90), fill=255)
self.author.putalpha(alpha_layer)
# gif列表
gifs = []
for i in range(len(jd)):
# 将参数传递给生成方法
# 添加到gif列表
gifs.append(self.add_png(jd[i]))
# 文件名,是否保存所有,图片列表,fps/ms
gifs[0].save("dem.gif","GIF",save_all=True,append_images=gifs, duration=35,loop=0)
self.author.close()
写上这个方法,否则在选择文件时,会弹出一个tk的默认界面
您可以注释掉以下两行以查看效果。<details><summary>*<font color='gray'>[En]</font>*</summary>*<font color='gray'>You can comment out the following two lines to see the effect.</font>*</details>
root = tkinter.Tk()
root.withdraw()
选择要生成的文件
可以替换为指定路径
file_path = filedialog.askopenfilename()
au = rua(file_path).add_gif()
本功能已集成到
源站地址:https://api.wer.plus
接口开发采用:Python + Flask
下载完整代码
Original: https://www.cnblogs.com/ymer/p/16248525.html
Author: 一·铭
Title: Python生成GIF动态图
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/499618/
转载文章受原作者版权保护。转载请注明原作者出处!