闲来无事,用几行代码下载了微信好友的全部头像,看了一下好友们的性别、个性签名,还挺有意思的,当然了,大家不嫌麻烦的可以继续探索一下做个可视化:好友性别比、城市统计、个性签名词云图......本篇文章只实现了下载好友头像,拼接头像图的功能。 首先需要安装:itchat、pillow。 1. 下载好友头像图片 getHeadImgs.py 下载很简单,只需要让itchat运行起来即可,需要自定义头像下载的路径path。 #!/usr/bin/env python3 #_*_ coding:utf-8 _*_ #__author__='阳光流淌007' #__date__ = '2018-03-06' import itchat itchat.auto_login() for friend in itchat.get_friends(update=True)[0:]: #可以用此句print查看好友的微信名、备注名、性别、省份、个性签名(1:男 2:女 0:性别不详) print(friend['NickName'],friend['RemarkName'],friend['Sex'],friend['Province'],friend['Signature']) img = itchat.get_head_img(userName=friend["UserName"]) path = "headImages/" + friend['NickName'] + "(" + friend['RemarkName'] + ").jpg" try: with open(path,'wb') as f: f.write(img) except Exception as e: print(repr(e)) itchat.run()
很快,头像就下载完了,我们可以点开文件夹欣赏了^_^,然后,可以做第二步—拼接头像图 2.拼接头像图 jointHeadImgs.py 拼接用到pillow库里的Image,然后譬如我有245个好友,那么为了保证我最终拼接的头像图是正方形的,我就只能拼15* 15 = 225张头像(每行15张头像),好友总数total不需要计算,因为total = len(pathList)可以获取好友头像图总数,行数line=15也不需要人为计算,因为line = int(sqrt(total))可以计算合适的行数。 唯一需要配置的,还是路径path(存放好友头像图的文件夹的路径) #!/usr/bin/env python3 #_*_ coding:utf-8 _*_ #__author__='阳光流淌007' #__date__ = '2018-03-06' import os from math import sqrt from PIL import Image #path是存放好友头像图的文件夹的路径 path = 'headImages/' pathList = [] for item in os.listdir(path): imgPath = os.path.join(path,item) pathList.append(imgPath) total = len(pathList)#total是好友头像图片总数 line = int(sqrt(total))#line是拼接图片的行数(即每一行包含的图片数量) NewImage = Image.new('RGB', (128*line,128*line)) x = y = 0 for item in pathList: try: img = Image.open(item) img = img.resize((128,128),Image.ANTIALIAS) NewImage.paste(img, (x * 128 , y * 128)) x += 1 except IOError: print("第%d行,%d列文件读取失败!IOError:%s" % (y,x,item)) x -= 1 if x == line: x = 0 y += 1 if (x+line*y) == line*line: break NewImage.save(path+"final.jpg")
程序运行完你会看到这个...final.jpg,点开看看,是不是感觉不错?!有木有准备拿到朋友圈去炫耀一番 PS:图侵删
|