tags:

views:

240

answers:

3

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

A: 

Use the textsize method (see docs) to figure out the dimensions of your text object before actually drawing it. Then draw it starting at the appropriate coordinates.

scrible
+2  A: 

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

jetxee
+2  A: 

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.

#!/usr/bin/env python
import Image
import ImageDraw
import ImageFont
import textwrap

astr='''The rain in Spain falls mainly on the plains.'''
para=textwrap.wrap(astr,width=15)

MAX_W,MAX_H=500,500
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', 36)

current_h=0
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

im.save('test.png')
unutbu