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 ):
Here I improved your code to do what you want:
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:
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. 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.
draw.text(xy=(template.width / 2, template.height / 2),
text=f"Hello, {name}", fill=(255, 255, 255), font=font_type,
anchor='mm')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.