PIL Text

You can use ImageDraw and ImageFont modules from PIL to add text to an image.

First you should obtain a TrueType font file (ends with “.ttf”).

Here’s an example of a font file from fonts.google.com:

OpenSans-Regular.ttf

Example Code

from PIL import Image, ImageDraw, ImageFont
img = Image.new('RGB', (400,300), 'white')

draw = ImageDraw.Draw(img)
opensans = ImageFont.truetype('OpenSans-Regular.ttf', 24)
draw.text((30, 100), "This text is blue.", font=opensans, fill='blue')
draw.text((30, 200), "Now some red text.", font=opensans, fill='red')

img.save('text_output.png')

This code will only work if you have the font file.

The example creates a new image as a background, but you can also use Image.open() to load an existing image.

Let’s look at the steps to make this work.
1) Upload/copy your ttf font file to the same folder as your Python code file.

2) Import ImageFont and ImageDraw along with Image.

from PIL import Image, ImageFont, ImageDraw

3) Load the font file to create a font object. You input the font filename as a string and the font size as an integer.

opensans = ImageFont.truetype('OpenSans-Regualr.ttf', 24)

4) Create a Draw object. This object named draw allows you to modify the Image object img by drawing lines, polygons, circles, text, and so on.

draw = ImageDraw.Draw(img)

5) Call the text() function of your Draw object. This modifies the image.

draw.text((30, 130), 'This is my text', font=opensans, fill='blue')

The first argument is the (x,y) coordinate pair where the text will be pasted. This represents the upper left corner of a rectangle containing the text. You must include the extra (parentheses).

The second argument is the text you want to add. Use quotes for string literals.

The font parameter is optional. If you leave it out, you will get a default font that doesn’t look the greatest.

The fill parameter (fill color) is optional. Text will be black if you leave that out.

You can read about other ImageDraw.text() options here:

ImageDraw.text() documentation

Locating Your Text / Centering

If you need help centering text, you have a few options:

a) Try a bunch of different (x, y) coordinates using trial and error until it looks right on your image.

b) Check the size of the text, especially the width. Then do the math to figure out where you want it in our image. For example, if your text is 100 pixels wide and you want it centered in your 500 pixel wide image, you need to start the text at x = 200 to center it horizontally. This is because (500 – 100) = 400 pixels of space on the outsides, and half of that space needs to be on each side.

Use ImageDraw.textsize() function to find the size of the your text.

size = draw.textsize('ABCDEFG', font=opensans)
print(size)

c) Define the anchor of your text according to the way you want it lined up. By default, the anchor is at the top left of your text, but you can defined it in other ways.

PIL Text Anchors Documentation