Skip to content

Commit

Permalink
fix: 修复文字转图片模块初始化时的bug
Browse files Browse the repository at this point in the history
  • Loading branch information
RockChinQ committed Jan 17, 2024
1 parent 2c5933d commit aa433bd
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
8 changes: 4 additions & 4 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,17 +175,17 @@ async def start_process(first_time_init=False):
except Exception as e:
print("更新openai库失败:{}, 请忽略或自行更新".format(e))

# 初始化文字转图片
from pkg.utils import text2img
text2img.initialize()

known_exception_caught = False
try:
try:

sh = reset_logging()
pkg.utils.context.context['logger_handler'] = sh

# 初始化文字转图片
from pkg.utils import text2img
text2img.initialize()

# 检查是否设置了管理员
if cfg['admin_qq'] == 0:
# logging.warning("未设置管理员QQ,管理员权限命令及运行告警将无法使用,如需设置请修改config.py中的admin_qq字段")
Expand Down
14 changes: 12 additions & 2 deletions pkg/utils/text2img.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
text_render_font: ImageFont = None

def initialize():
global text_render_font
logging.debug("初始化文字转图片模块...")
config = context.get_config_manager().data

if config['blob_message_strategy'] == "image": # 仅在启用了image时才加载字体
Expand All @@ -37,6 +39,8 @@ def initialize():
traceback.print_exc()
logging.error("加载字体文件失败({}),更换为转发消息组件以发送长消息,您可以在config.py中调整相关设置。".format(use_font))
config['blob_message_strategy'] = "forward"

logging.debug("字体文件加载完成。")


def indexNumber(path=''):
Expand Down Expand Up @@ -119,6 +123,8 @@ def compress_image(infile, outfile='', kb=100, step=20, quality=90):
def text_to_image(text_str: str, save_as="temp.png", width=800):
global text_render_font

logging.debug("正在将文本转换为图片...")

text_str = text_str.replace("\t", " ")

# 分行
Expand All @@ -128,9 +134,13 @@ def text_to_image(text_str: str, save_as="temp.png", width=800):
final_lines = []

text_width = width-80

logging.debug("lines: {}, text_width: {}".format(lines, text_width))
for line in lines:
logging.debug(type(text_render_font))
# 如果长了就分割
line_width = text_render_font.getlength(line)
logging.debug("line_width: {}".format(line_width))
if line_width < text_width:
final_lines.append(line)
continue
Expand Down Expand Up @@ -160,7 +170,7 @@ def text_to_image(text_str: str, save_as="temp.png", width=800):
img = Image.new('RGBA', (width, max(280, len(final_lines) * 35 + 65)), (255, 255, 255, 255))
draw = ImageDraw.Draw(img, mode='RGBA')


logging.debug("正在绘制图片...")
# 绘制正文
line_number = 0
offset_x = 20
Expand Down Expand Up @@ -192,7 +202,7 @@ def text_to_image(text_str: str, save_as="temp.png", width=800):

line_number += 1


logging.debug("正在保存图片...")
img.save(save_as)

return save_as

0 comments on commit aa433bd

Please sign in to comment.