繁体   English   中英

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

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

这是我的代码:

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

我想把文字放在中间。

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

在此处输入图像描述

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

在线尝试!

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:

在此处输入图像描述

Arty 建议的另一种方法是使用 Pillow 8 中实现的anchor参数。有关更多信息,请参阅有关文本锚点的 Pillow 文档 简而言之,值'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