diff --git a/config-template.py b/config-template.py index 73f50354..c1f19d6c 100644 --- a/config-template.py +++ b/config-template.py @@ -183,6 +183,12 @@ blob_message_threshold = 256 # - "forward": 将长消息转换为转发消息组件发送 blob_message_strategy = "forward" +# 文字转图片时使用的字体文件路径 +# 当策略为"image"时生效 +# 若在Windows系统下,程序会自动使用Windows自带的微软雅黑字体 +# 若未填写或不存在且不是Windows,将禁用文字转图片功能,改为使用转发消息组件 +font_path = "" + # 消息处理超时重试次数 retry_times = 3 diff --git a/pkg/utils/text2img.py b/pkg/utils/text2img.py index d5ee88b5..b21f72ec 100644 --- a/pkg/utils/text2img.py +++ b/pkg/utils/text2img.py @@ -1,8 +1,37 @@ +import logging + from PIL import Image, ImageDraw, ImageFont import re import os +import config +import traceback -text_render_font = ImageFont.truetype("res/simhei.ttf", 32, encoding="utf-8") +text_render_font: ImageFont = None + +if hasattr(config, "blob_message_strategy") and config.blob_message_strategy == "image": # 仅在启用了image时才加载字体 + use_font = config.font_path if hasattr(config, "font_path") else "" + try: + + # 检查是否存在 + if not os.path.exists(use_font): + # 若是windows系统,使用微软雅黑 + if os.name == "nt": + use_font = "C:/Windows/Fonts/msyh.ttc" + if not os.path.exists(use_font): + logging.warn("未找到字体文件,且无法使用Windows自带字体,更换为转发消息组件以发送长消息,您可以在config.py中调整相关设置。") + config.blob_message_strategy = "forward" + else: + logging.info("使用Windows自带字体:" + use_font) + text_render_font = ImageFont.truetype(use_font, 32, encoding="utf-8") + else: + logging.warn("未找到字体文件,且无法使用Windows自带字体,更换为转发消息组件以发送长消息,您可以在config.py中调整相关设置。") + config.blob_message_strategy = "forward" + else: + text_render_font = ImageFont.truetype(use_font, 32, encoding="utf-8") + except: + traceback.print_exc() + logging.error("加载字体文件失败({}),更换为转发消息组件以发送长消息,您可以在config.py中调整相关设置。".format(use_font)) + config.blob_message_strategy = "forward" def indexNumber(path=''): @@ -123,7 +152,7 @@ def text_to_image(text_str: str, save_as="temp.png", width=800): else: continue # 准备画布 - img = Image.new('RGBA', (width, max(280, len(final_lines) * 35 + 45)), (255, 255, 255, 255)) + img = Image.new('RGBA', (width, max(280, len(final_lines) * 35 + 65)), (255, 255, 255, 255)) draw = ImageDraw.Draw(img, mode='RGBA') diff --git a/res/simhei.ttf b/res/simhei.ttf deleted file mode 100644 index 5bd4687e..00000000 Binary files a/res/simhei.ttf and /dev/null differ