optimize image relevant logic
This commit is contained in:
parent
69dc818c73
commit
54d6c4da2d
Binary file not shown.
|
|
@ -11,6 +11,8 @@ import hashlib
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
|
import io
|
||||||
|
from PIL import Image, ImageChops
|
||||||
logger = logging.logger
|
logger = logging.logger
|
||||||
|
|
||||||
class Wechat:
|
class Wechat:
|
||||||
|
|
@ -51,6 +53,7 @@ class Wechat:
|
||||||
发送图片消息
|
发送图片消息
|
||||||
"""
|
"""
|
||||||
image_bytes = self.download_image(image_url)
|
image_bytes = self.download_image(image_url)
|
||||||
|
|
||||||
base64_str, md5_str = self.get_base64_and_md5(image_bytes)
|
base64_str, md5_str = self.get_base64_and_md5(image_bytes)
|
||||||
data = {
|
data = {
|
||||||
"msgtype": "image",
|
"msgtype": "image",
|
||||||
|
|
@ -74,9 +77,35 @@ class Wechat:
|
||||||
|
|
||||||
def download_image(self, image_url):
|
def download_image(self, image_url):
|
||||||
"""下载图片并返回 bytes"""
|
"""下载图片并返回 bytes"""
|
||||||
response = requests.get(image_url, timeout=10)
|
response = requests.get(image_url, timeout=300)
|
||||||
response.raise_for_status() # 抛出 HTTP 错误
|
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):
|
def get_base64_and_md5(self,image_bytes):
|
||||||
"""计算 Base64(不带 data: 前缀)和 MD5"""
|
"""计算 Base64(不带 data: 前缀)和 MD5"""
|
||||||
|
|
@ -96,6 +125,8 @@ class Wechat:
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
return response.json()
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def send_news(self, news: list):
|
def send_news(self, news: list):
|
||||||
"""
|
"""
|
||||||
发送图文消息
|
发送图文消息
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue