首页 > 编程 > Python > 正文

python itchat实现微信好友头像拼接图的示例代码

2019-11-25 15:56:24
字体:
来源:转载
供稿:网友

偶然在网上发现itchat这个框架,itchat是一个开源的微信个人号接口,它使python调用微信变得非常简单。看到网上有人发自己微信好友的头像拼接图,自己也做了一个,感觉还蛮好玩的。

效果图

下面介绍实现过程:

安装itchat

这个当然还是使用豆瓣源了,速度杠杠的pip install -i https://pypi.douban.com/simple/ itchat

项目依赖

头像拼接用到了pillow这个第三方库,和itchat一样的安装方法

代码

首先调用接口登录,然后可以获取到好友信息,其中第一个为自己的信息。返回的信息为一个列表,里面内容可以复制出来通过json工具格式化,查看返回的字段。然后再次调用接口下载图片,用pillow拼接即可。

import itchatimport mathimport osimport PIL.Image as Image#给auto_login方法传入值为真的hotReload.即使程序关闭,一定时间内重新开启也可以不用重新扫码itchat.auto_login(hotReload=True)friends = itchat.get_friends(update=True)#下载所有好友的头像图片num = 0for i in friends: img = itchat.get_head_img(i["UserName"]) with open('./headImg/' + str(num) + ".jpg",'wb') as f:  f.write(img)  f.close()  num += 1#获取文件夹内的文件个数length = len(os.listdir('./headImg'))#根据总面积求每一个的大小each_size = int(math.sqrt(float(810*810)/length))#每一行可以放多少个lines = int(810/each_size)#生成白色背景新图片image = Image.new('RGBA', (810, 810),'white')x = 0y = 0for i in range(0,length): try:  img = Image.open('./headImg/' + str(i) + ".jpg") except IOError:  print(i)  print("Error") else:  img = img.resize((each_size, each_size), Image.ANTIALIAS) #resize image with high-quality  image.paste(img, (x * each_size, y * each_size))  x += 1  if x == lines:   x = 0   y += 1image.save('./headImg/' + "all.jpg")#通过文件传输助手发送到自己微信中itchat.send_image('./headImg/' + "all.jpg",'filehelper')image.show()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表