Next / Previous / Contents / TCC Help System / NM Tech homepage

6. The ImageFont module

To specify fonts for the .text() method from the ImageDraw module, import this module:

    import ImageFont

You can then create a font object from any TrueType font by using this function:

ImageFont.truetype(file,size)

Returns a font object representing the TrueType font whose file name is given by the file argument, with a font height of size pixels.

Methods on font objects include:

.getsize(text)

For a given string text, returns a tuple (w,h) where w is the width in pixels that text will occupy on the display, and h its the height in pixels.

On Unix systems locally, TrueType fonts can be found in this directory:

/usr/share/fonts/

At this writing, there were two families of public-domain fonts:

Here's a complete program that creates a 200x50 gray image, writes text on it in red, and saves it to file runaway.jpg. File DejaVuLGCSansCondensed-Bold.ttf is sans-serif, condensed, bold font in the Deja Vu family.

#!/usr/local/bin/python
import Image
import ImageDraw
import ImageFont

fontPath = "/usr/share/fonts/dejavu-lgc/DejaVuLGCSansCondensed-Bold.ttf"
sans16  =  ImageFont.truetype ( fontPath, 16 )

im  =  Image.new ( "RGB", (200,50), "#ddd" )
draw  =  ImageDraw.Draw ( im )
draw.text ( (10,10), "Run awayyyy!", font=sans16, fill="red" )
im.save ( "runaway.jpg" )

On Windows systems, look in C:\WINDOWS\Fonts.