itchat+pillow實現微信好友頭像爬取和拼接
阿新 • • 發佈:2018-02-09
rsa ava itchat ioerror 縮小 獲取好友列表 con cmd body
源碼下載鏈接:https://pan.baidu.com/s/1cPZhwy 密碼:2t2o
###效果圖
使用方法:
下載項目到本地,打開項目主目錄,打開命令行,輸入:
pip install -r requirements.txt
使用pip命令時出了一個錯:You are using pip version 7.0.3, however version 9.0.1 is available. 解決方法: 使用easy_install指令安裝: 首先進入到easy_install的目錄 例如D:\Python\Scripts 然後通過指令 easy_install.exe pip==9.0.1 安裝成功。 之後又提示了一個錯誤: error: Unable to find vcvarsall.bat 解決方法: 我的python版本是3.6 ,網上多數解決方法是降級到2.X。不過我找到一個包,鏈接:https://pan.baidu.com/s/1pM6mdYj 密碼:s3mk 下載之後按照正常方式安裝, 裝完就解決了。
等待安裝完成,輸入:
python wxImage.py
出現如下二維碼:
用手機微信右上角的掃一掃,確認登陸即可。在微信的“文件傳輸助手”會收到你的好友頭像拼接圖(等待時間取決於你的好友數量)
核心
python:
- itchat(用於爬取頭像)
- pillow(用於拼接圖片)
##源碼詳解
首先登陸python版本微信itchat,生成二維碼:
itchat.auto_login(enableCmdQR=True)
獲取好友列表:
friends = itchat.get_friends(update=True)[0:]
然後使用itchat的get_head_img(userName=none)函數來爬取好友列表的頭像,並下載到本地:
num = 0 for i in friends: img = itchat.get_head_img(userName=i["UserName"]) fileImage= open(user + "/" + str(num) + ".jpg",‘wb‘) fileImage.write(img) fileImage.close() num += 1
計算出每張頭像縮小後的尺寸(由於為了拼接之後可以用來作為為微信頭像,所以合成的圖片大小都是640 * 640的,因為微信頭像大小就是640 * 640)
計算每張頭像縮小後的邊長(默認為正方形):
eachsize = int(math.sqrt(float(640 * 640) / numPic))
計算合成圖片每一邊分為多少小邊:
numline = int(640 / eachsize)
縮小並拼接圖片:
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 + ".jpg")
在微信的文件傳輸助手發合成後的圖片給使用者:
itchat.send_image(user + ".jpg", ‘filehelper‘)
###完整代碼:
from numpy import * import itchat import urllib import requests 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) + ".jpg",‘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 + ".jpg") itchat.send_image(user + ".jpg", ‘filehelper‘)
itchat+pillow實現微信好友頭像爬取和拼接