::: library ::: Python Imaging Library Handbook (2003 Edition)

Back   Next

On this page:

The ImageFont Module

The ImageFont module defines a class with the same name. Instances of this class store bitmap fonts, and are used with the text method of the ImageDraw class.

PIL uses it's own font file format to store bitmap fonts. You can use the pilfont utility to convert BDF and PCF font descriptors (X window font formats) to this format.

Starting with version 1.1.4, PIL can be configured to support TrueType and OpenType fonts. For earlier version, TrueType support is only available as part of the imToolkit package.


Here's a simple example:

import ImageFont, ImageDraw

font = ImageFont.load("arial.pil")

draw = ImageDraw.Draw(image)
draw.text((10, 10), "hello", font=font)



ImageFont.load(file) => Font instance

Loads a font from the given file, and returns the corresponding font object. If this function fails, it raises an IOError exception.


ImageFont.load_path(file) => Font instance

Same as load, but searches for the file along sys.path if it's not found in the current directory.


ImageFont.truetype(file, size) => Font instance

Load a TrueType or OpenType font file, and create a font object. This function loads a font object from the given file, and creates a font object for a font of the given size.

On Windows, if the given file name does not exist, the loader also looks in Windows fonts directory.

This function requires the _imagingft service.


ImageFont.load_default() => Font instance

(New in 1.1.4) Load a "better than nothing" default font.


Font objects must implement the following methods, which are used by the ImageDraw layer.


font.getsize(text) => (width, height)

Returns the width and height of the given text, as a 2-tuple.


font.getmask(text) => Image object

Returns a bitmap for the text. The bitmap should be an internal PIL storage memory instance (as defined by the Image.core interface module).

If the font uses antialiasing, the bitmap should have mode "L" and use a maximum value of 255. Otherwise, it should have mode "1".

Back   Next