您的位置:首页 > 编程语言 > Python开发

Python之itchat生成微信头像拼接问题

2017-11-26 14:16 691 查看

#coding=utf8
import itchat
import os

import PIL.Image as Image
from os import listdir
import math

itchat.auto_login(enableCmdQR=False)

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')


#运行

python wxImage.py

爬取完成,调用PIL库时候会提示无法生成JPEG

raise IOError("cannot write mode %s as JPEG" % im.mode)

IOError: cannot write mode RGBA as JPEG

#原因

查询资料,发现

其实是因为JPG图像有RGBA四个通道

所以调用含有A通道(透明度)方法/参数时候,程序不知道A通道怎么办,就会产生错误。

#解决办法

 调用  Image.new 该方法时候,传进‘RGB’,而不是‘RGBA’

Image.new('RGB', (640, 640))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 微信 utf-8 图片 jpg