有没有办法将图像上的文本居中(Python/PIL)?

时间:2021-04-05 12:48:29

标签: python python-imaging-library

这是我的代码:

from PIL import Image, ImageDraw, ImageFont
import names

name = names.get_first_name(gender="male")

template = Image.open("imgs/banner.png")
font_type = ImageFont.truetype("arial.ttf", 40)
draw = ImageDraw.Draw(template)
draw.text(xy=(50, 50), text=f"Hello, {name}", fill=(255, 255, 255), font=font_type)
template.save(f"banner-{name}.png")

我想将文本居中。

那是我的“模板”(original url):

enter image description here

2 个答案:

答案 0 :(得分:0)

在这里,我改进了您的代码以执行您想要的操作:

Try it online!

from PIL import Image, ImageDraw, ImageFont
import names

name = names.get_first_name(gender="male")

template = Image.open("banner.png")
font_type = ImageFont.truetype("arial.ttf", 40)
draw = ImageDraw.Draw(template)
text = f"Hello, {name}"
text_size = font_type.getsize(text)
draw.text(xy=(
    (template.size[0] - text_size[0]) // 2, (template.size[1] - text_size[1]) // 2),
    text=text, fill=(255, 255, 255), font=font_type)
template.save(f"banner-{name}.png")

输出:

enter image description here

答案 1 :(得分:0)

Arty 建议的替代方法是使用 Pillow 8 中实现的 anchor 参数。有关详细信息,请参阅 the Pillow documentation on text anchors。简而言之,值 'mm' 可用于围绕填充到 xy 参数的坐标水平和垂直对齐文本。

draw.text(xy=(template.width / 2, template.height / 2),
          text=f"Hello, {name}", fill=(255, 255, 255), font=font_type,
          anchor='mm')

banner with centered text