根据 需求,将文字写成图片
from PIL import Image, ImageDraw, ImageFont
def text_to_image(text1, text2, output_path, font_path="simhei.ttf", font_size=10, image_width=333,
background_color=(255, 255, 255)):
"""
将两个字符串生成图片并保存,第一个文本结束后画一条线。
支持字符串中的 \n 换行符。
参数:
text1 (str): 第一个字符串(蓝色)。
text2 (str): 第二个字符串(黑色)。
output_path (str): 图片保存的路径(例如 "output.png")。
font_path (str): 字体文件路径,默认为 "simhei.ttf"。
font_size (int): 字体大小,默认为 10。
image_width (int): 图片宽度,默认为 333。
background_color (tuple): 背景颜色,默认为白色 (255, 255, 255)。
"""
# 每行最多 26 个字
chars_per_line = 26
# 计算行数(支持 \n 换行符)
def split_text(text):
lines = []
# 先按 \n 分割
paragraphs = text.split('\n')
for paragraph in paragraphs:
# 再按每行 26 个字分割
for i in range(0, len(paragraph), chars_per_line):
lines.append(paragraph[i:i + chars_per_line])
return lines
lines1 = split_text(text1) # 第一个字符串的行数
lines2 = split_text(text2) # 第二个字符串的行数
total_lines = len(lines1) + len(lines2) # 总行数
# 计算图片高度(每行高度为字体大小 + 5 像素的间距)
line_height = font_size + 5
image_height = total_lines * line_height + 40 # 上下留白 20 像素 + 线的额外空间
# 创建图片
image = Image.new('RGB', (image_width, image_height), background_color)
draw = ImageDraw.Draw(image)
# 加载字体
try:
font = ImageFont.truetype(font_path, font_size)
except IOError:
raise ValueError(f"字体文件 '{font_path}' 未找到,请提供正确的字体文件路径。")
# 绘制第一个字符串(蓝色)
text_color1 = (0, 0, 255) # 蓝色
y = 10 # 起始纵坐标
for line in lines1:
draw.text((10, y), line, font=font, fill=text_color1)
y += line_height # 换行
# 在第一个文本结束后画一条线
line_y = y + 5 # 线距离第一个文本 5 像素
draw.line((10, line_y, image_width - 10, line_y), fill=(0, 0, 0), width=1) # 黑色线
y = line_y + 10 # 线距离第二个文本 10 像素
# 绘制第二个字符串(黑色)
text_color2 = (0, 0, 0) # 黑色
for line in lines2:
draw.text((10, y), line, font=font, fill=text_color2)
y += line_height # 换行
# 保存图片
image.save(output_path)
print(f"图片已保存到: {output_path}")
# 显示图片(可选)
# image.show()
if __name__ == '__main__':
# 定义两个字符串(包含 \n 换行符)
text1 = "这是第一个字符串,颜色为蓝色。\n这是一个示例文本,用于测试多行文字的左对齐效果。"
text2 = "这是第二个字符串,颜色为黑色。\n这是另一段示例文本,用于测试图片高度的动态计算功能。"
# 调用函数生成图片
text_to_image(
text1=text1, # 第一个字符串(蓝色)
text2=text2, # 第二个字符串(黑色)
output_path="output.png", # 图片保存路径
font_path="simhei.ttf", # 字体文件路径
font_size=16, # 字体大小
image_width=430 # 图片宽度
)