It's also possible to use other fonts with the text() function. To do so, first create an ImageFont object. The ImageFont object is part of PIL, and to import it, issue from PIL import ImageFont. Once ImageFont is imported, you can use a font with a call to ImageFont.truetype(fontname, size). The returned ImageFont object can be passed as an argument to the text() function by means of the font argument.
Of course, to be able to use fonts, they must first be installed in your system. Windows typically comes with built-in fonts; and on Linux fonts are usually installed with X (as well as other applications). You can also use fonts from the GNU FreeFont project (http://www.gnu. org/software/freefont/).
However, font and font names are different on varying systems, and not just different operating systems: my Windows system might have different fonts than your Windows system. This means calling ImageFont.truetype(fontname, size) might work on one system and not on another. To overcome this problem, I use the function findfont(), which is part of the matplotlib.font_manager module. The function findfont() returns a string with the location of a font that best matches the requested font.
The following script annotates text with the Vera font using the findfont() function:
>>> from matplotlib import font_manager
>>> from PIL import Image, ImageDraw, ImageFont
>>> font_str = font_manager.findfont('Vera')
'/usr/lib/python2.5/site-packages/matplotlib/mpl-data/fonts/ttf/Vera.ttf' >>> ttf = ImageFont.truetype(font_str, 54) >>> s = 'ABCabc'
>>> draw.text(((250-w)/2, (l00-h)/2), 'ABCabc', font = ttf)
The first two statements import the proper objects from PIL as well as matplotlib's font manager. I then create a one-band image of size (250, 100) followed by the instantiation of an ImageDraw object attached to the image.
Next I use matplotlib's findfont() function to find a font that's closest to the font Vera. The path to the font is stored in the string font str. Following that I create an ImageFont object named ttf and use that font object to render the text. I then calculate the size of the text and render it in the middle of a gray background, as shown in Figure 9-3.
Figure 9-3. Font rendering
Was this article helpful?