1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 用python把微信好友头像拼成一张图

用python把微信好友头像拼成一张图

时间:2023-02-15 04:14:32

相关推荐

用python把微信好友头像拼成一张图

首先需要用到三个库:

wxpy库(用于获取好友头像然后下载)、pillow库(用于拼接头像)、pyinstaller库(用于打包python程序成exe文件)

这里我说一下创建虚拟环境的步骤:

我先要提醒一点,下面的操作你应该先找到pycharmprojects目录下的Scripts文件夹(里面得有pip文件)

1.安装pipenv和pyinstaller包,用于后续创建虚拟环境和打包程序

pip install pipenvpip install pyinstaller

2.选择一个合适的目录作为python虚拟环境

pipenv install #创建虚拟环境pipenv shell #进入虚拟环境

3.安装程序引用的库(wxpy,math,os,pillow)

pipenv install wxpy math os

4.打包运行程序

程序代码如下:

from wxpy import *import mathfrom PIL import Imageimport os# 创建头像存放文件夹def creat_filepath():avatar_dir = os.getcwd() + "\\wechat\\"if not os.path.exists(avatar_dir):os.mkdir(avatar_dir)return avatar_dir# 保存好友头像def save_avatar(avatar_dir):# 初始化机器人,扫码登陆bot = Bot()friends = bot.friends(update=True)num = 0for friend in friends:friend.get_avatar(avatar_dir + '\\' + str(num) + ".jpg")print('好友昵称:%s' % friend.nick_name)num = num + 1# 拼接头像def joint_avatar(path):# 获取文件夹内头像个数length = len(os.listdir(path))# 设置画布大小image_size = 2560# 设置每个头像大小each_size = math.ceil(2560 / math.floor(math.sqrt(length)))# 计算所需各行列的头像数量x_lines = math.ceil(math.sqrt(length))y_lines = math.ceil(math.sqrt(length))image = Image.new('RGB', (each_size * x_lines, each_size * y_lines))x = 0y = 0for (root, dirs, files) in os.walk(path):for pic_name in files:# 增加头像读取不出来的异常处理try:with Image.open(path + pic_name) as img:img = img.resize((each_size, each_size))image.paste(img, (x * each_size, y * each_size))x += 1if x == x_lines:x = 0y += 1except IOError:print("头像读取失败")img = image.save(os.getcwd() + "/wechat.png")print('微信好友头像拼接完成!')if __name__ == '__main__':avatar_dir = creat_filepath()save_avatar(avatar_dir)joint_avatar(avatar_dir)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。