1. 程式人生 > >Python3 生成微信好友頭像的圖片合集

Python3 生成微信好友頭像的圖片合集

lis code chat 頭像 ant except 加密 nump 登陸

剛才在github上看到一個大神寫的生成微信好友圖像集合的腳本
自己運行了一下發現挺好玩的

原帖地址:https://github.com/aloneZERO/py-party/tree/master/wechat-imgs
#!python3
# coding: utf-8

import itchat
import os

from PIL import Image
import math


# 首先登陸python版本微信itchat,生成二維碼
# itchat.auto_login(enableCmdQR=True)
itchat.auto_login()

# 獲取好友列表
friends = itchat.get_friends(update=True)[0:]

# 以自己的用戶名加密碼創建文件夾來存儲圖片
user = friends[0]["UserName"]
print("User Code: "+user)
os.mkdir(user)

# 使用itchat的get_head_img(userName=none)函數
# 爬取好友列表的頭像,並下載到本地
num = 0
for i in friends:
    img = itchat.get_head_img(userName=i["UserName"])
    with open(user + "/" + str(num) + ".jpg", 'wb') as fileImage:
        fileImage.write(img)
    num += 1

# 計算好友數量
pics = os.listdir(user)
numPic = len(pics)
print("好友總數:"+str(numPic))

# 計算每張頭像縮小後的邊長(默認為正方形)
eachsize = int(math.sqrt(float(640 * 640) / numPic))
# print(eachsize)

# 計算合成圖片每一邊分為多少小邊
numline = int(640 / eachsize)
toImage = Image.new('RGBA', (640, 640))
# print(numline)

# 縮小並拼接圖片
x, y = 0, 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("funny.jpg")
itchat.send_image("funny.jpg", 'filehelper')
print("好友頭像拼接完畢,快去查看吧~")

Python3 生成微信好友頭像的圖片合集