How would I center-align (and middle-vertical-align) text when using PIL?
Advertisement
Answer
Deprecation Warning: textsize is deprecated and will be removed in Pillow 10 (2023-07-01). Use textbbox or textlength instead.
Code using textbbox
instead of textsize
.
JavaScript
x
11
11
1
from PIL import Image, ImageDraw, ImageFont
2
3
4
def create_image(size, bgColor, message, font, fontColor):
5
W, H = size
6
image = Image.new('RGB', size, bgColor)
7
draw = ImageDraw.Draw(image)
8
_, _, w, h = draw.textbbox((0, 0), message, font=font)
9
draw.text(((W-w)/2, (H-h)/2), message, font=font, fill=fontColor)
10
return image
11
JavaScript
1
5
1
myFont = ImageFont.truetype('Roboto-Regular.ttf', 16)
2
myMessage = 'Hello World'
3
myImage = create_image((300, 200), 'yellow', myMessage, myFont, 'black')
4
myImage.save('hello_world.png', "PNG")
5
Result
Use Draw.textsize
method to calculate text size and re-calculate position accordingly.
Here is an example:
JavaScript
1
12
12
1
from PIL import Image, ImageDraw
2
3
W, H = (300,200)
4
msg = "hello"
5
6
im = Image.new("RGBA",(W,H),"yellow")
7
draw = ImageDraw.Draw(im)
8
w, h = draw.textsize(msg)
9
draw.text(((W-w)/2,(H-h)/2), msg, fill="black")
10
11
im.save("hello.png", "PNG")
12
and the result:
If your fontsize is different, include the font like this:
JavaScript
1
3
1
myFont = ImageFont.truetype("my-font.ttf", 16)
2
draw.textsize(msg, font=myFont)
3