所以我正在尝试使用 python 将标准文本文件转换为带有文本的图像,这是我正在使用的脚本。
from PIL import Image, ImageDraw, ImageFont
import textwrap
def draw_multiple_line_text(image, text, font, text_color, text_start_height):
'''
From unutbu on [python PIL draw multiline text on image](https://stackoverflow.com/a/7698300/395857)
'''
draw = ImageDraw.Draw(image)
image_width, image_height = image.size
y_text = text_start_height
lines = textwrap.wrap(text, width=40)
for line in lines:
line_width, line_height = font.getsize(line)
draw.text(((image_width - line_width) / 2, y_text),
line, font=font, fill=text_color)
y_text += line_height
def main():
'''
Testing draw_multiple_line_text
'''
#image_width
image = Image.new('RGB', (800, 600), color = (255, 255, 255))
fontsize = 30 # starting font size
font = ImageFont.truetype("FreeMono.ttf", fontsize)
#open text file in read mode
text_file = open("text.txt", "r")
#read whole file to a string
text1 = text_file.read()
text_color = (0, 0, 0)
text_start_height = 10
draw_multiple_line_text(image, text1, font, text_color, text_start_height)
#draw_multiple_line_text(image, text2, font, text_color, 400)
image.save('text.png')
if __name__ == "__main__":
main()
#cProfile.run('main()') # if you want to do some profiling
但是我习惯于在 Gimp 上执行此任务,我遇到的问题是我希望能够修改标准行间距和字母间距。