简体   繁体   English

有什么方法可以将图像上的文本居中(Python/PIL)?

[英]Is there any way to middle the text on the image (Python/PIL)?

Here is my code:这是我的代码:

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")

I would like to middle the text.我想把文字放在中间。

Thats my "template" ( original url ):那是我的“模板”(原始 url ):

在此处输入图像描述

Here I improved your code to do what you want:在这里,我改进了您的代码以执行您想要的操作:

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")

Output: Output:

在此处输入图像描述

An alternative approach to the one suggested by Arty is to use the anchor parameter implemented in Pillow 8. See the Pillow documentation on text anchors for more information. Arty 建议的另一种方法是使用 Pillow 8 中实现的anchor参数。有关更多信息,请参阅有关文本锚点的 Pillow 文档 In short, the value 'mm' can be used to both horizontally and vertically align the text around the coordinates filled in to the xy argument.简而言之,值'mm'可用于水平和垂直对齐填充到xy参数的坐标周围的文本。

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

带有居中文本的横幅

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM