Pillow supports drawing text on your images in addition to shapes. Pillow uses its own font file format to store bitmap fonts, limited to 256 characters. Pillow also supports TrueType and OpenType fonts as well as other font formats supported by the FreeType library.

In this chapter, you will learn about the following:

  • Drawing Text
  • Loading TrueType Fonts
  • Changing Text Color
  • Drawing Multiple Lines of Text
  • Aligning Text
  • Changing Text Opacity
  • Learning About Text Anchors

While this article is not completely exhaustive in its coverage of drawing text with Pillow, when you have finished reading it, you will have a good understanding of how text drawing works and be able to draw text on your own.

Let’s get started by learning how to draw text.

Drawing Text

Drawing text with Pillow is similar to drawing shapes. However, drawing text has the added complexity of needing to be able to handle fonts, spacing, alignment, and more. You can get an idea of the complexity of drawing text by taking a look at the text() function’s signature:

This function takes in a lot more parameters than any of the shapes you can draw with Pillow! Let’s go over each of these parameters in turn:

  • xy - The anchor coordinates for the text (i.e. where to start drawing the text).
  • text - The string of text that you wish to draw.
  • fill - The color of the text (can a tuple, an integer (0-255) or one of the supported color names).
  • font - An ImageFont instance.
  • anchor - The text anchor alignment. Determines the relative location of the anchor to the text. The default alignment is top left.
  • spacing - If the text is passed on to multiline_text(), this controls the number of pixels between lines.
  • align - If the text is passed on to multiline_text()"left""center" or "right". Determines the relative alignment of lines. Use the anchor parameter to specify the alignment to xy.
  • direction - Direction of the text. It can be "rtl" (right to left), "ltr" (left to right) or "ttb" (top to bottom). Requires libraqm.
  • features - A list of OpenType font features to be used during text layout. Requires libraqm.
  • language - The language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a BCP 47 language code. Requires libraqm.
  • stroke_width - The width of the text stroke
  • stroke_fill - The color of the text stroke. If you don’t set this, it defaults to the fill parameter’s value.
  • embedded_color - Whether to use font embedded color glyphs (COLR or CBDT).

#python #web dev #images #text #pillow

Drawing Text on Images With Pillow and Python
5.55 GEEK