Python3之好友矩阵图

简单介绍下本篇文章幕后小背景吧——

某周末,炒鸡热

吃完中午饭,和某人在家静静地呆着刷剧,听着窗外似有若无的知了虫鸣

突然,脑中灵光闪现,想起了最近正在鼓捣的PIL

于是转头冲某人邪魅一笑:想不想 炸一波 朋!友!圈!?

某人:蛤?

··· ···


说干就干!小本本小本本抱过来!小板凳小板凳坐起来!

确认语言环境:Pyhton3

####-第一步-

pip导入需要用到的四个库

import itchat
import os
import math
import PIL.Image as Image

####-第二步-

指定好友头像缓存目录,因为头像文件数量比较多,所以在当前路径下添加目录 ‘/img/’ ;若无此目录,捕获 FileNotFoundError 异常,创建目录,继续调用函数。

# 好友头像缓存路径
IMG_DIR = os.getcwd() + '/img/'

# 下载好友头像
def download_imgs(firends):
    num = 1
    try:
        for firend in firends:
            img_name = str(num) + '.jpg'
            img = itchat.get_head_img(userName=firend['UserName'])
            with open(IMG_DIR + img_name, 'wb') as file:
                file.write(img)
            print(u'已下载:%d' % num)
            num += 1
        return num
    except FileNotFoundError:
        os.mkdir(IMG_DIR)
        return download_imgs(firends)

####-第三步-

process_imgs() 比较简单,主要是读取头像缓存目录,加工处理获取:

头像列表头像总计数列数行数
img_listimg_nummax_columnmax_row

列数与行数为总计数平方根向下取整,所以余出来的好友将会无情的被抛除于矩阵之外。

# 加工头像列表信息
def process_imgs():
    # 头像列表
    img_list = []

    for root, dirs, files in os.walk(IMG_DIR):
        for file in files:
            if "jpg" in file and os.path.getsize(os.path.join(root, file)) > 0:
                img_list.append(os.path.join(root, file))

    img_num = len(img_list)

    max_column = int(math.sqrt(img_num))
    max_row = int(math.sqrt(img_num))

    return img_list, img_num, max_column, max_row

####-第四步-

万事具备!就差这一哆嗦!

准备好合成图像保存路径 MERGE_PATH

设置好单个好友头像等比例压缩参数 HEAD_IMG_WIDTHHEAD_IMG_HEIGHT

# 合成矩阵图保存路径(例如:A/B/C)
MERGE_PNG = '/heiheipiupiupiu.png'
MERGE_PATH = 'A/B/C' + MERGE_PNG
# 好友头像压缩(数字越大,合成图像质量越高)
HEAD_IMG_WIDTH = 80
HEAD_IMG_HEIGHT = 80

# 合成好友头像矩阵图
def merge_imgs():
    img_list, img_num, max_line, max_row = process_imgs()
    print(max_line, max_row, img_num)

    num = 0
    imgs_count = max_line * max_row

    # 创建空白画板
    white_board = Image.new('RGBA', (HEAD_IMG_WIDTH * max_line, HEAD_IMG_HEIGHT * max_row))

    # 逐行列绘制好友头像
    for i in range(0, max_row):
        for j in range(0, max_line):

            head_img = Image.open(img_list[num])
            # 等比例压缩头像
            temp_head_img = head_img.resize((HEAD_IMG_WIDTH, HEAD_IMG_HEIGHT))
            # 绘画位置
            place = (int(j % max_row * HEAD_IMG_WIDTH), int(i % max_row * HEAD_IMG_HEIGHT))
            # 绘制粘贴
            white_board.paste(temp_head_img, place)

            num = num + 1
            if num >= len(img_list):
                break

        if num >= imgs_count:
            break

    print(white_board.size)
    white_board.save(MERGE_PATH)

####-第五步-

做事手脚干净些,清除好友头像缓存,不给机器内存添麻烦

# 清除好友头像缓存
def clean_imgs(path):
    for img in os.listdir(path):
        i = os.path.join(path, img)
        if os.path.isfile(i):
            os.remove(i)

####-第六步-

照例加上主函数,获取好友信息列表,使线程优雅地运转起来,泡上一杯清茶···

下载,呦呦呦

好嘞!

合成!走你~

清~除~

if __name__ == '__main__':
    itchat.auto_login(hotReload=True)
    #好友列表
    firends = itchat.get_friends(update=True)
    print('[···开始下载好友头像···]')
    num = download_imgs(firends)
    count = num - 1
    print(u'[···头像下载完成,总计下载数量为:%d···]' % count)

    print('[···开始合成好友头像···]')
    merge_imgs()
    print('[···合成好友头像完成···]')

    print('[···开始清除好友头像缓存···]')
    clean_imgs(IMG_DIR)
    print('[···清除缓存完成···]')

小可爱,快返回你的合成图像保存路径下看看吧!拿出那张图片,你就可以去盆友圈**分(zhuang)享(bi)**了···

像这样:(保护好友隐私,另加深度模糊处理,真实程序暂不支持模糊特效噢)
这里写图片描述

有更多精彩或想提问题可扫下方二维码,关注后台私M。随缘回复,无量天尊

公众号:陆玖神通

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值