1 | initial version |
To align PIL text to the center, you can use the textwidth
and textheight
attributes of the font to calculate the position of the text. Here's an example:
from PIL import Image, ImageDraw, ImageFont
# Create a blank image
image = Image.new('RGB', (500, 500), 'white')
# Get a font
font = ImageFont.truetype('arial.ttf', 36)
# Get the size of the text
text = 'Hello, world!'
textwidth, textheight = draw.textsize(text, font)
# Calculate the position of the text
x = (image.width - textwidth) / 2
y = (image.height - textheight) / 2
# Draw the text
draw = ImageDraw.Draw(image)
draw.text((x, y), text, font=font, fill='black')
# Show the image
image.show()
This will create an image with the text "Hello, world!" centered horizontally and vertically.