Files
HeXi/hexi/plugins/nonebot_plugin_dailywife/utils/avatar.py
T

57 lines
1.7 KiB
Python
Raw Normal View History

"""今日老婆 —— 头像工具(纯工具 + 网络请求)。"""
from __future__ import annotations
import hashlib
from io import BytesIO
import httpx
from PIL import Image
# PNG 重绘大小
def png_resize(source_file, new_width=0, new_height=0, resample="LANCZOS", ref_file=""):
img = source_file
img = img.convert("RGBA")
width, height = img.size
if ref_file != "":
imgRef = Image.open(ref_file)
new_width, new_height = imgRef.size
else:
if new_height == 0:
new_height = new_width * width / height
bands = img.split()
resample_map = {
"NEAREST": Image.NEAREST,
"BILINEAR": Image.BILINEAR,
"BICUBIC": Image.BICUBIC,
"LANCZOS": Image.LANCZOS,
}
resample_method = resample_map.get(resample, Image.LANCZOS)
bands = [b.resize((new_width, new_height), resample=resample_method) for b in bands]
return Image.merge("RGBA", bands)
async def download_url(url: str) -> bytes:
from nonebot import logger
async with httpx.AsyncClient() as client:
for i in range(3):
try:
resp = await client.get(url)
if resp.status_code != 200:
continue
return resp.content
except Exception as e:
logger.error(f"Error downloading {url}, retry {i}/3: {str(e)}")
return b""
async def download_avatar(user_id: str) -> bytes:
url = f"http://q1.qlogo.cn/g?b=qq&nk={user_id}&s=640"
data = await download_url(url)
if not data or hashlib.md5(data).hexdigest() == "acef72340ac0e914090bd35799f5594e":
url = f"http://q1.qlogo.cn/g?b=qq&nk={user_id}&s=100"
data = await download_url(url)
return data