From a457d13d2c4f09998545234bc29303a559155ff0 Mon Sep 17 00:00:00 2001 From: Rock Chin <1010553892@qq.com> Date: Sat, 4 Mar 2023 23:53:22 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E4=BC=98=E5=8C=96=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E6=B8=B2=E6=9F=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/qqbot/blob.py | 9 +++++++-- pkg/utils/text2img.py | 13 +++++++------ 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/pkg/qqbot/blob.py b/pkg/qqbot/blob.py index 2ac6a4b..c6edff2 100644 --- a/pkg/qqbot/blob.py +++ b/pkg/qqbot/blob.py @@ -1,4 +1,5 @@ # 长消息处理相关 +import logging import os import time import base64 @@ -54,7 +55,10 @@ def text_to_image(text: str) -> MessageComponent: # 删除图片 os.remove(img_path) - os.remove(compressed_path) + + # 判断compressed_path是否存在 + if os.path.exists(compressed_path): + os.remove(compressed_path) # 返回图片 return Image(base64=b64.decode('utf-8')) @@ -67,7 +71,8 @@ def check_text(text: str) -> list: if len(text) > config.blob_message_threshold: if not hasattr(config, 'blob_message_strategy'): raise AttributeError('未定义长消息处理策略') - + + # logging.info("长消息: {}".format(text)) if config.blob_message_strategy == 'image': # 转换成图片 return [text_to_image(text)] diff --git a/pkg/utils/text2img.py b/pkg/utils/text2img.py index b18cd7e..d5ee88b 100644 --- a/pkg/utils/text2img.py +++ b/pkg/utils/text2img.py @@ -70,7 +70,7 @@ def compress_image(infile, outfile='', kb=100, step=20, quality=90): """ o_size = get_size(infile) if o_size <= kb: - return infile + return infile, o_size outfile = get_outfile(infile, outfile) while o_size > kb: im = Image.open(infile) @@ -82,9 +82,10 @@ def compress_image(infile, outfile='', kb=100, step=20, quality=90): return outfile, get_size(outfile) -def text_to_image(text_str, save_as="temp.png", width=800): +def text_to_image(text_str: str, save_as="temp.png", width=800): global text_render_font - # 文字分行 + + text_str = text_str.replace("\t", " ") # 分行 lines = text_str.split('\n') @@ -92,7 +93,7 @@ def text_to_image(text_str, save_as="temp.png", width=800): # 计算并分割 final_lines = [] - text_width = width-40 + text_width = width-80 for line in lines: # 如果长了就分割 line_width = text_render_font.getlength(line) @@ -122,14 +123,14 @@ def text_to_image(text_str, save_as="temp.png", width=800): else: continue # 准备画布 - img = Image.new('RGBA', (width, max(280, len(final_lines) * 35 + 35)), (255, 255, 255, 255)) + img = Image.new('RGBA', (width, max(280, len(final_lines) * 35 + 45)), (255, 255, 255, 255)) draw = ImageDraw.Draw(img, mode='RGBA') # 绘制正文 line_number = 0 offset_x = 20 - offset_y = 20 + offset_y = 30 for final_line in final_lines: draw.text((offset_x, offset_y + 35 * line_number), final_line, fill=(0, 0, 0), font=text_render_font) # 遍历此行,检查是否有emoji