[英]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.