Python 制作微信全家福

https://mp.weixin.qq.com/s?__biz=MzU0OTU5OTI4MA==&mid=2247487008&idx=2&sn=8621ad10badb900ad2e700927e947c4c&chksm=fbac2f7fccdba6691cc5d12353e955cf8486c5ab88d2f94bed7dc04e2aba307a6c551bb235e2&scene=21#wechat_redirect

目录:0 引言  1 环境 2 代码实现 3 后记

 

0 引言

前段时间,微信朋友圈开始出现了一种晒照片新形式,微信好友墙,即在一张大图片中展示出自己的所有微信好友的头像。

效果如下图,出于隐私考虑,这里作了模糊处理。

是不是很炫,而且这还是独一无二的,毕竟每个人的微信好友是不一样的。本文就教大家用Python来实现这种效果。

 

1 环境

操作系统:Windows

Python版本:3.7.3

 

2 代码实现

我们需要首先需要获取好友的头像信息,接下来处理图像并完成图像的拼接。

 

2.0 准备工作

在这里,我们登录微信获取好友信息,使用的是 wxpy 模块;处理并生成最终的图像借助 PIL 模块。因为都是第三方模块,如环境中没有可以使用 pip 进行安装。另外涉及路径的处理等,我们需要导入 os 模块和 sys 模块。

 

from wxpy import *
import PIL.Image as Image
import os
import sys

 

2.1 获取并存储好友头像信息

我们要获取微信好友的头像,首先需要登录微信

 
 

# 初始化机器人,扫码登陆微信,适用于Windows系统
bot = Bot()

# # Linux系统,执行登陆请调用下面的这句
# bot = Bot(console_qr=2, cache_path="botoo.pkl"

在获取好友头像信息之前,我们得先在本地创建一个目录,用于后续存储好友头像的文件。

 
 

# 获取当前路径信息
curr_dir = get_dir(sys.argv[0])
# 如果FriendImgs目录不存在就创建一个
if not os.path.exists(curr_dir + "FriendImgs/"):
    os.mkdir(curr_dir + "FriendImgs/")

接下来就是获取友头像信息,并将其存储在本地创建的目录中。

 
 

my_friends = bot.friends(update=True)
# 获取好友头像信息并存储在FriendImgs目录中
n = 0
for friend in my_friends:
    friend.get_avatar(curr_dir + "FriendImgs/" + str(n) + ".jpg")
    n = n + 1

这时你就可以在本地FriendImgs文件夹中,看到保存下来的微信好友头像的图片。

 

2.2 生成微信好友墙

制作微信好友墙,就像以前的大字报,把我们下载的好友头像逐一贴上去即可。

首先设定好微信好友墙的尺寸,使用 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))
        # 设置每一行排13个图像
        x += 1
        if x == 13:
            x = 0
            y += 1
# 保存图片为WeChat_Friends.jpg
img = image.save(curr_dir + "WeChat_Friends.jpg

代码执行后,最终生成的效果图如下:

(这里展示的图片做了模糊处理)

 

3 后记

本文中设定照片墙尺寸为650*650,而好友头像尺寸为50*50,这样最终制作成的照片墙每行有13位好友,共计容纳13*13位好友。

大家可根据自己实际情况,自行调整尺寸参数,以达到最佳效果。大家赶快去生成自己独一无二的照片墙吧!从此你就是朋友最亮的仔!

公众号后台回复「照片墙」即可获取本文全部代码。

发布了91 篇原创文章 · 获赞 47 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_30007885/article/details/102481869