optimize image relevant logic

This commit is contained in:
blade 2025-11-03 13:20:57 +08:00
parent 69dc818c73
commit 54d6c4da2d
2 changed files with 33 additions and 2 deletions

View File

@ -11,6 +11,8 @@ import hashlib
import json
import os
import time
import io
from PIL import Image, ImageChops
logger = logging.logger
class Wechat:
@ -51,6 +53,7 @@ class Wechat:
发送图片消息
"""
image_bytes = self.download_image(image_url)
base64_str, md5_str = self.get_base64_and_md5(image_bytes)
data = {
"msgtype": "image",
@ -74,9 +77,35 @@ class Wechat:
def download_image(self, image_url):
"""下载图片并返回 bytes"""
response = requests.get(image_url, timeout=10)
response = requests.get(image_url, timeout=300)
response.raise_for_status() # 抛出 HTTP 错误
return response.content
image_bytes = response.content
# 得到图片的长与宽
image_width, image_height = self.get_image_width_and_height(image_bytes)
if image_width > 720 or image_height > 720:
# 如果图片长宽大于720则缩小图片
# 计算缩放比例
scale = 720 / max(image_width, image_height)
new_width = int(image_width * scale)
new_height = int(image_height * scale)
# 缩放图片
image = Image.open(io.BytesIO(image_bytes))
image.thumbnail((new_width, new_height), Image.Resampling.LANCZOS)
# 将缩放后的图片保存为bytes
img_byte_arr = io.BytesIO()
# 保持原始格式如果是RGBA格式则保存为PNG否则保存为JPEG
if image.mode in ('RGBA', 'LA', 'P'):
image.save(img_byte_arr, format='PNG')
else:
image.save(img_byte_arr, format='JPEG', quality=95)
image_bytes = img_byte_arr.getvalue()
return image_bytes
def get_image_width_and_height(self, image_bytes):
"""得到图片的长与宽"""
image = Image.open(io.BytesIO(image_bytes))
width, height = image.size
return width, height
def get_base64_and_md5(self,image_bytes):
"""计算 Base64不带 data: 前缀)和 MD5"""
@ -96,6 +125,8 @@ class Wechat:
response.raise_for_status()
return response.json()
def send_news(self, news: list):
"""
发送图文消息