How to insert text to image using Python

edit  Updated by

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.

We can use ImageFont and ImageDraw to insert text to an image using Python

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

img = Image.open("sample_image.jpg")
draw = ImageDraw.Draw(img)
# font = ImageFont.truetype(<font-file>, <font-size>)
# If a font is already installed in your system, you can 
# just give its name
font = ImageFont.truetype("arial", 24)
# draw.text((x, y),"Sample Text",(r,g,b))
# x, y is the top-left coordinate
draw.text((0, 0),"Hello world",(255,255,255),font=font)
img.save('sample-out.jpg')

The above code writes “Hello world” text to the existing image called sample_image.jpg

To create new blank white image and then add the black text to it, let change a little bit

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

img = Image.new('L', (window_height, window_width), color='white')
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("arial", 24)
draw.text((0, 0), "Hello world", font=font)
img.save('sample-out.jpg')

See Also