Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center-/middle-align text with PIL?

How would I center-align (and middle-vertical-align) text when using PIL?

like image 506
Phillip B Oldham Avatar asked Dec 28 '09 18:12

Phillip B Oldham


People also ask

How do you center text in the middle?

Select the text that you want to center. in the Page Setup group, and then click the Layout tab. In the Vertical alignment box, click Center. In the Apply to box, click Selected text, and then click OK.

How do you center align text in Python?

Python String center() MethodThe center() method will center align the string, using a specified character (space is default) as the fill character.

How do I align text in the middle of a box?

Right-click the text box for which you want to set vertical alignment. On the shortcut menu, click Format Text Box. In the Format Text Box dialog box, click the Text Box tab. In the Vertical alignment box, select Top, Middle, or Bottom.

Which command is used to center align the text?

To make text centred, select and highlight the text first, then hold down Ctrl (the control key) on the keyboard and press E.


2 Answers

Use Draw.textsize method to calculate text size and re-calculate position accordingly.

Here is an example:

from PIL import Image, ImageDraw  W, H = (300,200) msg = "hello"  im = Image.new("RGBA",(W,H),"yellow") draw = ImageDraw.Draw(im) w, h = draw.textsize(msg) draw.text(((W-w)/2,(H-h)/2), msg, fill="black")  im.save("hello.png", "PNG") 

and the result:

image with centered text

If your fontsize is different, include the font like this:

myFont = ImageFont.truetype("my-font.ttf", 16) draw.textsize(msg, font=myFont) 
like image 140
sastanin Avatar answered Oct 12 '22 20:10

sastanin


Here is some example code which uses textwrap to split a long line into pieces, and then uses the textsize method to compute the positions.

from PIL import Image, ImageDraw, ImageFont import textwrap  astr = '''The rain in Spain falls mainly on the plains.''' para = textwrap.wrap(astr, width=15)  MAX_W, MAX_H = 200, 200 im = Image.new('RGB', (MAX_W, MAX_H), (0, 0, 0, 0)) draw = ImageDraw.Draw(im) font = ImageFont.truetype(     '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', 18)  current_h, pad = 50, 10 for line in para:     w, h = draw.textsize(line, font=font)     draw.text(((MAX_W - w) / 2, current_h), line, font=font)     current_h += h + pad  im.save('test.png') 

enter image description here

like image 22
unutbu Avatar answered Oct 12 '22 20:10

unutbu