How to add text to an image using pillow in Python

How to Add Text to an Image with Pillow in Python

In this article, we’ll see how to add text to an image using the Pillow library in Python. Python The Python Imaging Library (PIL) is the de facto image processing package for the Python language. It integrates lightweight image processing tools that help edit, create, and save images. Pillow supports many image file formats, including BMP, PNG, JPEG, and TIFF.

Methods Used

Syntax:

ImageDraw.Draw.text((x, y),"Text",(r,g,b))

Steps

  • Import module
  • Import image
  • Add text
  • Save image

Image in Use:

How to add text to an image using pillow in Python?

Example 1:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
  
# Importing the image
img = Image.open("gfg.png")
draw = ImageDraw.Draw(img)
  
# Specifying coordinates and color of text
draw.text((50, 90), "Sample Text", (255, 255, 255))
  
# Saving the image
img.save('sample.jpg')

Output:

How to add text to an image using Pillow in Python?

Example 2: Writing Text in a Specific Font

To write text in a specific font, we need to download the required font file. In the following example, we use Comic Sans, which can be downloaded from: https://www.wfonts.com/font/comic-sans-ms

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

# Importing the image
img = Image.open("gfg.png")
draw = ImageDraw.Draw(img)

# Loading the font and providing the size
font = ImageFont.truetype("ComicSansMS3.ttf", 30)

# Specifying the coordinates and color of the text
draw.text((50, 90), "Hello World!", (255, 255, 255), font=font)

# Saving the image
img.save('sample.jpg')

Output:

How to add text to an image using Pillow in Python?

Leave a Reply

Your email address will not be published. Required fields are marked *