首页 > 解决方案 > 用文字完美填充图像

问题描述

我想创建一个带有 PILLOW 的图像,其中填充了文本。

我不知道如何设置完美的行数和字体大小来做到这一点。

这是我需要的渲染示例:

在此处输入图像描述

我正在处理的代码:

from PIL import Image, ImageDraw, ImageFont
import textwrap


def draw_multiple_line_text(image, text, font, text_color, text_start_height):
    draw = ImageDraw.Draw(image)
    image_width, image_height = image.size
    y_text = text_start_height
    lines = textwrap.wrap(text, width=60)
    for line in lines:
        line_width, line_height = font.getsize(line)
        print(line_width, line_height)
        draw.text(((image_width - line_width) / 2, y_text), line, font=font, fill=text_color)
        y_text += line_height


def main():
    image = Image.new('RGB', (500, 500), color=(0, 0, 0))
    fontsize = 20  # starting font size
    font = ImageFont.truetype("arial.ttf", fontsize)
    text = "No, woman, no cry No, woman, no cry No, woman, no cry No, woman, no cry 'Cause, 'cause, 'cause I remember when we used to sit In the government yard in Trenchtown Oba observing the 'ypocrites Mingle with the good people we meet Good friends we have, oh, good friends we've lost Along the way In this great future, you can't forget your past So dry your tears, I seh No, woman, no cry No, woman, no cry 'Ere, little darlin', don't shed no tears No, woman, no cry Said, said, said, I remember when-a we used to sit In the government yard in Trenchtown And then Georgie would make the fire lights, I seh A log wood burnin' through the night Then we would cook cornmeal porridge, I seh Of which I'll share with you My feet is my only carriage And so I've got to push on through… "

    text_color = (200, 200, 200)
    text_start_height = 0
    draw_multiple_line_text(image, text, font, text_color, text_start_height)
    image.save('pil_text.png')


if __name__ == "__main__":
    main()

当前渲染:

在此处输入图像描述

预先感谢您的帮助。

标签: pythonpython-imaging-library

解决方案


不是字体和大小的问题;事实上,对于大多数文本,这些选择不足以提供完美的填充。

仔细查看目标文本:完美来自在每行的单词之间插入适当的空格。你必须仔细阅读文本,尽可能地填写每一行。一旦确定了换行符所属的位置,就进行第二次遍历,根据需要分配空格以将最右边的字符扩展到右边距。

为此,您计算不足,将其除以单位空间的宽度(这与字体不同),然后将这些空间均匀地分配到文本中的现有空间。“均匀”是您选择的过程。


推荐阅读