一键拼出你的微信好友图片墙

核心是利用两个库:

wxpy 库,用于获取好友头像然后下载

Pillow 库,用于拼接头像

直接上代码(源码来自公众号 高级农名工)

 1 # coding=utf8
 2 from wxpy import *
 3 import math
 4 from PIL import Image
 5 import os
 6 # 创建头像存放文件夹
 7 def creat_filepath():
 8     avatar_dir = os.getcwd() + "\\wechat\\"
 9     if not os.path.exists(avatar_dir):
10         os.mkdir(avatar_dir)
11     return avatar_dir
12  
13 # 保存好友头像
14 def save_avatar(avatar_dir):
15     # 初始化机器人,扫码登陆
16     bot = Bot()
17     friends = bot.friends(update=True)
18     num = 0
19     for friend in friends:
20         friend.get_avatar(avatar_dir + '\\' + str(num) + ".jpg")
21         print('好友昵称:%s' % friend.nick_name)
22         num = num + 1
23  
24 # 拼接头像
25 def joint_avatar(path):
26     # 获取文件夹内头像个数
27     length = len(os.listdir(path))
28     # 设置画布大小
29     image_size = 2560
30     # 设置每个头像大小
31     each_size = math.ceil(2560 / math.floor(math.sqrt(length)))
32     # 计算所需各行列的头像数量
33     x_lines = math.ceil(math.sqrt(length))
34     y_lines = math.ceil(math.sqrt(length))
35     image = Image.new('RGB', (each_size * x_lines, each_size * y_lines))
36     x = 0
37     y = 0
38     for (root, dirs, files) in os.walk(path):
39         for pic_name in files:
40             # 增加头像读取不出来的异常处理
41                 try:
42                     with Image.open(path + pic_name) as img:
43                         img = img.resize((each_size, each_size))
44                         image.paste(img, (x * each_size, y * each_size))
45                         x += 1
46                         if x == x_lines:
47                             x = 0
48                             y += 1
49                 except IOError:
50                     print("头像读取失败")
51  
52     img = image.save(os.getcwd() + "/wechat.png")
53     print('微信好友头像拼接完成!')
54  
55 if __name__ == '__main__':
56     avatar_dir = creat_filepath()
57     save_avatar(avatar_dir)
58     joint_avatar(avatar_dir)

 

posted @ 2020-04-18 17:37  与夜色融为一体  阅读(360)  评论(0编辑  收藏  举报