Adding Text to Images in Python using the PIL Library

AuthorSumit Dey Sarkar

Pubish Date30 Apr 2023

categoryPython

In this tutorial we will learn how to add text to image in Python using the PIL library.

 

Adding Text to Images in Python using the PIL Library

 

Adding text to images in Python using the PIL library

You can add text on an image using the Python Imaging Library (PIL).

 

Here an example that shows how to do this.

from PIL import Image, ImageDraw, ImageFont

# Load the image
image = Image.open('image.jpg')

# Create a drawing object
draw = ImageDraw.Draw(image)

# Define the text to be drawn and the font to be used
text = 'Hello, World!'
font = ImageFont.truetype('arial.ttf', 36)

# Determine the size of the text
text_width, text_height = draw.textsize(text, font)

# Calculate the x,y coordinates of the text
x = (image.width - text_width) / 2
y = (image.height - text_height) / 2

# Draw the text on the image
draw.text((x, y), text, font=font, fill=(255, 255, 255))

# Save the modified image
image.save('output.jpg')

 

Using the Image.open() method, we first load an image in this example. The text is then drawn onto the image using an ImageDraw object that we later construct. We define the text to be drawn and the font to be used using the ImageFont.truetype() method. Using the ImageDraw.textsize() method, we estimate the text's size before calculating its x and y coordinates. Finally, we use the ImageDraw.text() function to add text to the image, and the Image.save() method to save the altered image.

Comments 0

Leave a comment