How to add text on an image using pillow in python ?

How to add text on an image using pillow in python ?

Daidalos May 09, 2020


Example of how to add text on an image using pillow in python:

1 -- Create an image with pillow and add text on it

Example 1: let's for example create a simple image with a red background:

from PIL import Image

img = Image.new('RGB', (600, 400), color = 'red')

img.save('pil_red.png')

How to add text on an image using pillow in python ?

To add text, you must first download a 'font' file locally to your machine, for example for Times Roman [times-ro.ttf] (https://www.download-free-fonts.com/details/86847/ times-roman) (freely available font files can be found on the web). We can then add text to the figure using the "Times Roman" font like this:

from PIL import Image 
from PIL import ImageFont
from PIL import ImageDraw

font = ImageFont.truetype("times-ro.ttf", 24)

img = Image.new('RGB', (600, 400), color = 'red')

draw = ImageDraw.Draw(img)
draw.text((300, 200),"Hello World !",(0,0,0),font=font)

img.save('pil_red.png')

How to add text on an image using pillow in python ?

2 -- Use an existing image and add text with pillow

from PIL import Image 
from PIL import ImageFont
from PIL import ImageDraw

font = ImageFont.truetype("times-ro.ttf", 34)

img = Image.open('eiffel-tower.jpeg')

draw = ImageDraw.Draw(img)
draw.text((100, 200),"Hello Paris !",(0,0,0),font=font)

img.save('eiffel_tower_02.png')

How to add text on an image using pillow in python ?

3 -- References