下面是我的代码:
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):
发布于 2021-04-05 21:02:43
在这里,我改进了你的代码来做你想做的事情:
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")
输出:
发布于 2021-04-05 21:09:49
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')
https://stackoverflow.com/questions/66953315
复制相似问题