实现-微信好友头像排列成文字(附带源码)
首先给你们看看实现出来的效果!
实现--操作步骤:
1、点击单点单图:
2、输入相应文字和保存的文件夹:
3、点击获取微信头像并微信授权下载微信好友头像结束后直接点击输出文件就可以了
源码介绍:
核心是利用三个个库:
wxpy 库,用于获取好友头像然后下载
Pillow 库,用于拼接头像
Pyinstaller 库,用来打包 Python 程序成 exe 文件
程序通过三个函数实现,第一个 creat_filepath 函数生成图片下载文件路径,第二个 save_avatar 函数循环获取微信好友头像然后保存到本地,第三个 joint_avatar 函数就是把头像拼接成一张大图。
完整源码:
# -*- coding: utf-8 -*-
from wxpy import *
import math
from PIL import Image
import 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 = 0
for 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 = 0
y = 0
for (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 += 1
if x == x_lines:
x = 0
y += 1
except 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)
from wxpy import *
import math
from PIL import Image
import 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 = 0
for 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 = 0
y = 0
for (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 += 1
if x == x_lines:
x = 0
y += 1
except 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)
完整项目打包发给大家下载:
公众号扫入回复--“微信头像”即可--->获取源码