Python adds text to the picture
Adding Text to an Image with Python
In daily life, we often need to add text to images, such as adding a date and time to a photo or adding a watermark. Python is a powerful programming language and provides many libraries for image processing. In this article, we will introduce how to add text to an image using Python.
PIL Library Introduction
PIL (Python Imaging Library) is a powerful image processing library in Python. It provides many image processing functions, including opening, saving, cropping, rotating, and scaling images. In Python 3, the PIL library was updated to Pillow, so we need to install the Pillow library for image processing.
You can install the Pillow library using the following command:
pip install pillow
Adding Text to an Image
First, we need to import the ImageFont, ImageDraw, and Image modules from the Pillow library. Then, we can use the text method from the ImageDraw library to add text to the image. The following is a simple example code:
from PIL import Image, ImageDraw, ImageFont
# Open an image
image = Image.open("example.jpg")
draw = ImageDraw.Draw(image)
# Set the font and text
font = ImageFont.truetype("arial", 36)
text = "Hello, World!"
# Add text to the image
draw.text((10, 10), text, fill=(255, 255, 255), font=font)
# Save the image
image.save("output.jpg")
In this example, we open an image named “example.jpg” and create an ImageDraw object. We then set the font and the text to be added. Next, we use the draw.text method to add text at coordinates (10, 10) in the image. Finally, we save the new image containing the added text.