Python Pillow - Writing Text on Image


Advertisements

You can write text on images by passing the location of the text, the text itself and the color of the text. We can pass multiple other parameters to this method.

Example

from PIL import Image, ImageDraw

img = Image.open(beach1.jpg')
d1 = ImageDraw.Draw(img)
d1.text((28, 36), "Hello, Howcodex!", fill=(255, 0, 0))
img.show()
img.save("images/image_text.jpg")

Input

Howcodex

Output

If you save the above program as Example.py and execute, it will add the given text on it, and displays it using the standard PNG display utility, as follows −

Howcodex1

Selecting the font

There are numerous ways to select the font used for writing on the image. We can either load fonts directly from the system by passing the full path to the function, or we can use the ImageFont to load a TrueType font.

Example

from PIL import Image, ImageDraw, ImageFont

img = Image.open('images/logo.jpg')
d1 = ImageDraw.Draw(img)
myFont = ImageFont.truetype('E:/PythonPillow/Fonts/FreeMono.ttf', 40)
d1.text((0, 0), "Sample text", font=myFont, fill =(255, 0, 0))
img.show()
img.save("images/image_text.jpg")

Output

Howcodex2
Advertisements