
相信微信大家是用得再多也不过了。那么,对于python+微信,又能玩出什么新的花样呢?下面小编就给大家带来一个好玩的东西。用python下载所有的微信好友的头像,然后拼接成一张大图。这样,大家就可以转载到朋友圈装XY了。哈哈。
还是先给大家看看效果图如何。毕竟无图言X。

好了废话不多说,看看我们是怎么一步一步做出来的吧。
from wxpy import *
from PIL import Image
import os
import math
# 创建头像存放文件夹
def create_file_path():
avater_dir = os.path.join(os.getcwd(),'wechat')
if not os.path.exists(avater_dir):
os.mkdir(avater_dir)
return avater_dir
# 获取所有的好友头像并保存
def save_wx_avater(avater_dir):
bot = Bot(cache_path=True)
friends = bot.friends(update=True)
num = 0
for friend in friends:
friend.get_avatar(os.path.join(avater_dir,f'{str(num)}.jpg'))
print("好友昵称:%s"%friend.name)
num += 1
# 拼接头像
def joint_wx_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 = 0
y = 0
for (root, dirs, files) in os.walk(path):
for pic_name in files:
# 增加头像读取不出来的异常处理
try:
with Image.open(os.path.join(path, pic_name)) as img:
img = img.resize((each_size, each_size))
image.paste(img, (x * each_size, y * each_size))
x += 1
if x == x_lines:
x = 0
y += 1
except Exception as e:
print(F"头像读取失败,错误:{e}")
img = image.save(os.path.join(os.getcwd(), 'wechat.png'))
print('微信好友头像拼接完成!')
if __name__ == '__main__':
avatar_dir = create_file_path()
save_wx_avater(avatar_dir)
joint_wx_avatar(avatar_dir)参考:https://www.cnblogs.com/Yang-Sen/p/10875092.html