前段时间,微信朋友圈开始出现了一种晒照片新形式,微信好友墙,即在一张大图片中展示出自己的所有微信好友的头像。是不是很炫,而且这还是独一无二的,毕竟每个人的微信好友是不一样的。本文就教大家用Python来实现这种效果。我们需要首先需要获取好友的头像信息,接下来处理图像并完成图像的拼接。在这里,我们登录微信获取好友信息,使用的是 wxpy 模块;处理并生成最终的图像借助 PIL 模块。因为都是第三方模块,如环境中没有可以使用 pip 进行安装。另外涉及路径的处理等,我们需要导入 os 模块和 sys 模块。from wxpy import *
import PIL.Image as Image
import os
import sys
在获取好友头像信息之前,我们得先在本地创建一个目录,用于后续存储好友头像的文件。
curr_dir = get_dir(sys.argv[0])
if not os.path.exists(curr_dir + "FriendImgs/"):
os.mkdir(curr_dir + "FriendImgs/")
接下来就是获取友头像信息,并将其存储在本地创建的目录中。my_friends = bot.friends(update=True)
n = 0
for friend in my_friends:
friend.get_avatar(curr_dir + "FriendImgs/" + str(n) + ".jpg")
n = n + 1
这时你就可以在本地FriendImgs文件夹中,看到保存下来的微信好友头像的图片。
制作微信好友墙,就像以前的大字报,把我们下载的好友头像逐一贴上去即可。首先设定好微信好友墙的尺寸,使用 Image.new() 方法。image = Image.new("RGB", (650, 650))
接下来,我们需要逐个打开微信好友的图片,使用 Image.open() 方法。img = Image.open(curr_dir + "FriendImgs/" + file_names)
将微信头像图片,重置为50*50像素尺寸的小图,使用 img.resize() 方法。img = img.resize((50, 50), Image.ANTIALIAS)
然后将图片黏贴到我们的照片墙中,使用 image.paste() 方法。image.paste(img, (x * 50, y * 50))
最后将制作完成的照片墙保存下来,使用 image.save() 方法。
img = image.save(curr_dir + "WeChat_Friends.jpg")
image = Image.new("RGB", (650, 650))
x = 0
y = 0
curr_dir = get_dir(sys.argv[0])
ls = os.listdir(curr_dir + 'FriendImgs')
for file_names in ls:
try:
img = Image.open(curr_dir + "FriendImgs/" + file_names)
except IOError:
continue
else:
img = img.resize((50, 50), Image.ANTIALIAS)
image.paste(img, (x * 50, y * 50))
x += 1
if x == 13:
x = 0
y += 1
img = image.save(curr_dir + "WeChat_Friends.jpg
本文中设定照片墙尺寸为650*650,而好友头像尺寸为50*50,这样最终制作成的照片墙每行有13位好友,共计容纳13*13位好友。大家可根据自己实际情况,自行调整尺寸参数,以达到最佳效果。大家赶快去生成自己独一无二的照片墙吧!从此你就是朋友最亮的仔!我在 GitHub 上都见过哪些沙雕项目?
比 Selenium 更好用的新神器 Pyppeteer!