[Image-SIG] centering graphical text with PIL?

coen at reservoir.nl coen at reservoir.nl
Tue Dec 12 02:02:51 CET 2006


Hello, 
Here is a little something. Maybe it's ugly code but I'm not a programmer. I just make things that work for me! :)
Enjoy, Coen.

import Image, ImageDraw, ImageFont
import aggdraw

width = 500
height = 300

mijntekst = "Python"

im = Image.new("RGB", (width, height), ("white"))
draw = aggdraw.Draw(im)
font = aggdraw.Font(("red"), "georgiaz.ttf", 72, opacity=180)

# Getting the size of you text
mijntekstformaat = draw.textsize(mijntekst, font)
textwidth, textheight = mijntekstformaat
halftextwidth = 0.5 * textwidth
halftextheight = 0.5 * textheight

# Position of text on the canvas
x = 0.5 * width
y = 0.5 * height

# Just a little bit up and to the left
x1 = x - halftextwidth
y1 = y - halftextheight

draw.text((x1, y1), mijntekst, font)
draw.flush()

#  im.save ('myfilename.png', 'png')
im.show()



More information about the Image-SIG mailing list