首先是在python3 下运行的效果,调用itchat模块进行爬取微信上的头像,调用pillow,用于拼接头像
如果没有安装itchat,可以通过命令行安装:pip install itchat
实现微信好友头像爬取和拼接的效果:
import itchat
import os
import PIL.Image as Image
from os import listdir
import math
itchat.auto_login(enableCmdQR=True)
friends = itchat.get_friends(update=True)[0:]
user = friends[0]["UserName"]
print(user)
os.mkdir(user)
num = 0
for i in friends:
img = itchat.get_head_img(userName=i["UserName"])
fileImage = open(user + "/" + str(num) + ".png",'wb')
fileImage.write(img)
fileImage.close()
num += 1
pics = listdir(user)
numPic = len(pics)
print(numPic)
eachsize = int(math.sqrt(float(640 * 640) / numPic))
print(eachsize)
numline = int(640 / eachsize)
toImage = Image.new('RGBA', (640, 640))
print(numline)
x = 0
y = 0
for i in pics:
try:
#打开图片
img = Image.open(user + "/" + i)
except IOError:
print("Error: 没有找到文件或读取文件失败")
else:
#缩小图片
img = img.resize((eachsize, eachsize), Image.ANTIALIAS)
#拼接图片
toImage.paste(img, (x * eachsize, y * eachsize))
x += 1
if x == numline:
x = 0
y += 1
toImage.save(user + ".png")
itchat.send_image(user + ".png", 'filehelper')
cannot write mode rgba as jpg
- 这是因为,JPG只有三个通道,而程序中一定用到了RGBA四个通道,所以程序不知道多出来的一个通道怎么处理,就会报错了。
解决方法:
1.PNG图像有RGBA四个通道,而BMP和JPG图像只有RGB三个通道,所以我们可以将程序中所有图片的保存形式改为PNG
2 不想改变图片格式,就添加判断,进行转换
if len(toImage.split())==4:
r,g,b,a=toImage.split() #利用split和merge将通道从四个转换为三个
toImage=Image.merge("RGB",(r,g,b))
toImage.save(user + ".jpg")