通過python中的itchat+pillow實現微信好友頭像爬取和拼接

首先是在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格式進行了更改成png,解決如下:
  • 這是因爲,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")   
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章