手把手教你微信好友头像形成指定的文字

手把手教你微信好友头像形成指定的文字

实现-微信好友头像排列成文字(附带源码

首先给你们看看实现出来的效果(输入文字“暑假快乐”)!

      

     

 

实现步骤解析:

1、点击单点单图:

2、输入相应文字和保存的文件夹:

3、点击获取微信头像并微信授权下载微信好友头像结束后直接点击输出文件就可以了

3、打开你输入的文件名称的输出文件:例如我输入的是RunWsh,那么文字对应头像图片在RunWsh_输出文件里

源码介绍:

核心是利用三个个库:

1 wxpy 库,用于获取好友头像然后下载
2 
3  
4 
5 Pillow 库,用于拼接头像
6 
7  
8 
9 Pyinstaller 库,用来打包 Python 程序成 exe 文件

程序通过三个函数实现,第一个 creat_filepath 函数生成图片下载文件路径,第二个 save_avatar 函数循环获取微信好友头像然后保存到本地,第三个 joint_avatar 函数就是把头像拼接成一张大图。

完整源码:

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

 完整项目打包发给大家下载:

公众号扫入回复--“微信头像”即可--->获取源码

  

原文地址:https://www.cnblogs.com/chenqiwei/p/RunWsh_WechatHead.html