首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有没有办法在图片中居中显示文字(Python/PIL)?

有没有办法在图片中居中显示文字(Python/PIL)?
EN

Stack Overflow用户
提问于 2021-04-05 20:48:29
回答 2查看 85关注 0票数 1

下面是我的代码:

代码语言:javascript
运行
复制
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):

EN

回答 2

Stack Overflow用户

发布于 2021-04-05 21:02:43

在这里,我改进了你的代码来做你想做的事情:

Try it online!

代码语言:javascript
运行
复制
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")

输出:

票数 0
EN

Stack Overflow用户

发布于 2021-04-05 21:09:49

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

代码语言:javascript
运行
复制
draw.text(xy=(template.width / 2, template.height / 2),
          text=f"Hello, {name}", fill=(255, 255, 255), font=font_type,
          anchor='mm')

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66953315

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档