Python picture plus word PIL
Python Image and Text PIL
Introduction
PIL (Python Imaging Library) is a powerful image processing library that can be used to open, manipulate, and save various image file formats. In this article, we’ll explain how to add text to https://coder-cafe.com/wp-content/uploads/2025/09/images using the PIL library.
Installing the PIL Library
First, we need to install the PIL library. If you’re using Python 2.x, you can install it using the following command:
pip install Pillow
If you’re using Python 3.x, you can install it using the following command:
pip install Pillow
Example Code
The following is a simple example code demonstrating how to add text to an image:
from PIL import Image, ImageDraw, ImageFont
# Open an image file
image = Image.open('example.jpg')
# Create an object that can draw text on the image
draw = ImageDraw.Draw(image)
# Set the text's position, content, and color
text = "Hello, World!"
position = (10, 10)
color = (255, 255, 255)
# Load the font file
font = ImageFont.truetype('arial.ttf', 36)
# Draw text on the image
draw.text(position, text, fill=color, font=font)
# Save the processed image
image.save('result.jpg')
In this code, we first open an image named example.jpg
and create a drawing object draw
to draw text on the image. We then set the text to Hello, World!
and specify the position, color, and font. Finally, we call the draw.text()
method to draw the text on the image and save the processed image as the result.jpg
file.