Home > front end >  Python pillow put text in center/middle
Python pillow put text in center/middle

Time:08-20

I am trying to put the text always in middle from very side. and i found this solution, but it doesnt work when i make the font size bigger.

I found this solution, it doesnt work too: Center-/middle-align text with PIL?

This is my snippets:

from PIL import Image, ImageFont, ImageDraw 
import textwrap


W, H = (2480,1754)
msg = "hello"
bg_color = "yellow"
font_name = 'Helvetica Neu Bold.ttf'
font_size = 500

im = Image.new("RGBA",(W,H), bg_color)
draw = ImageDraw.Draw(im)
myFont = ImageFont.truetype(font_name, font_size)

w, h = draw.textsize(msg)


# y_text=(H/2)-130

draw.text(((W-font_size)/2,(H-font_size)/2), msg, fill="black", font=myFont)

im.save("hello.png", "PNG")

The output is below: Click to see output

Can anyone help me how can i put it in middle?

CodePudding user response:

I think, change:

w, h = draw.textsize(msg)

draw.text(((W-font_size)/2,(H-font_size)/2), msg, fill="black", font=myFont)

to:

w, h = draw.textsize(msg, font=myFont)

draw.text(((W-w)/2,(H-h)/2), msg, fill="black", font=myFont)

You are calculating the position from the font_size (500), but you need to be calculating from how big the message will be when written in myFont, at that font_size, and that is the (w, h) you get from asking draw.textsize() and giving it the font to work with.

  • Related