The Pillow library in Python makes it easy to add text to images.
This is useful for watermarking, creating banners, memes, or overlaying captions on images.
In this tutorial, we’ll cover:
1. Installing Pillow
To install Pillow, use the following command:
pip install pillow
2. Adding Basic Text to an Image
Use the ImageDraw module to draw text on images.
Example: Basic Text Overlay
from PIL import Image, ImageDraw # Open an image image = Image.open("example.jpg") # Create a drawing object draw = ImageDraw.Draw(image) # Add text to the image draw.text((50, 50), "Hello, World!", fill="white") # Save and show the image image.save("text_overlay.jpg") image.show()
Explanation
- draw.text((x, y), text, fill=color):
- (x, y) specifies the position of the text.
- text is the string to be drawn.
- fill defines the color of the text.
3. Customizing Text Appearance
To change the font style and size, use the ImageFont module.
Example: Custom Fonts
from PIL import Image, ImageDraw, ImageFont # Open an image image = Image.open("example.jpg") # Create a drawing object draw = ImageDraw.Draw(image) # Load a custom font font = ImageFont.truetype("arial.ttf", size=40) # Add text with the custom font draw.text((50, 50), "Custom Font", font=font, fill="yellow") # Save and show the image image.save("custom_font.jpg") image.show()
Notes
- Replace “arial.ttf” with the path to your desired font file.
- Use size to adjust the font size.
4. Positioning Text
To center text or position it precisely, calculate its dimensions using textsize().
Example: Centered Text
# Get the image dimensions width, height = image.size # Define the text and font text = "Centered Text" font = ImageFont.truetype("arial.ttf", size=40) # Calculate text width and height text_width, text_height = draw.textsize(text, font=font) # Calculate position x = (width - text_width) // 2 y = (height - text_height) // 2 # Add centered text draw.text((x, y), text, font=font, fill="blue") image.save("centered_text.jpg") image.show()
5. Adding Multiline Text
The multiline_text() method is used to add multiple lines of text.
Example: Multiline Text
multiline_text = """This is an example of multiline text using Pillow.""" draw.multiline_text((50, 50), multiline_text, font=font, fill="green", spacing=10) image.save("multiline_text.jpg") image.show()
Options
- spacing: Adjusts the space between lines.
- align: Can be set to “left”, “center”, or “right” for alignment.
6. Using Transparent Backgrounds
You can create an image with a transparent background and overlay text.
Example: Transparent Background
from PIL import Image, ImageDraw, ImageFont # Create a new image with transparent background transparent_image = Image.new("RGBA", (400, 200), (255, 255, 255, 0)) # Create a drawing object draw = ImageDraw.Draw(transparent_image) # Define text and font text = "Transparent Text" font = ImageFont.truetype("arial.ttf", size=40) # Add text to the transparent image draw.text((50, 50), text, font=font, fill=(255, 255, 255, 128)) # Semi-transparent white # Save the transparent image transparent_image.save("transparent_text.png") transparent_image.show()
7. Creating Watermarks
Watermarks can be added by overlaying semi-transparent text on an image.
Example: Adding a Watermark
# Open an image image = Image.open("example.jpg").convert("RGBA") # Create a transparent overlay overlay = Image.new("RGBA", image.size, (255, 255, 255, 0)) draw = ImageDraw.Draw(overlay) # Define the watermark text and font watermark_text = "Watermark" font = ImageFont.truetype("arial.ttf", size=50) # Add the watermark text to the overlay width, height = image.size text_width, text_height = draw.textsize(watermark_text, font=font) x = width - text_width - 20 y = height - text_height - 20 draw.text((x, y), watermark_text, font=font, fill=(255, 255, 255, 128)) # Combine the overlay with the image watermarked_image = Image.alpha_composite(image, overlay) # Save and show the watermarked image watermarked_image.save("watermarked_image.png") watermarked_image.show()
8. Batch Text Overlay on Multiple Images
You can automate text overlay for multiple images in a directory.
Example: Batch Processing
import os def add_text_to_images(input_folder, output_folder, text, font_path, font_size): os.makedirs(output_folder, exist_ok=True) for filename in os.listdir(input_folder): if filename.endswith((".jpg", ".png", ".jpeg")): image = Image.open(os.path.join(input_folder, filename)) draw = ImageDraw.Draw(image) font = ImageFont.truetype(font_path, size=font_size) draw.text((50, 50), text, font=font, fill="red") image.save(os.path.join(output_folder, filename)) print(f"Processed: {filename}") # Example usage add_text_to_images("input_images", "output_images", "Batch Text", "arial.ttf", 30)
9. Practical Examples
9.1 Creating a Meme
# Add a caption at the bottom meme_text = "When you code with Pillow" font = ImageFont.truetype("impact.ttf", size=50) text_width, text_height = draw.textsize(meme_text, font=font) x = (width - text_width) // 2 y = height - text_height - 20 draw.text((x, y), meme_text, font=font, fill="white") image.save("meme.jpg") image.show()
9.2 Adding Dynamic Information
import datetime # Add current date and time to the image current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") draw.text((10, 10), current_time, font=font, fill="yellow") image.save("timestamped_image.jpg") image.show()
10. Summary
Key Methods
- ImageDraw.Draw(): Create a drawing object.
- draw.text(): Add text to the image.
- draw.multiline_text(): Add multiline text.
- ImageFont.truetype(): Load custom fonts.
Common Use Cases
- Adding captions to images.
- Creating watermarked images.
- Annotating images with dynamic information.
- Generating memes or banners.
Experiment with these examples and customize them to your needs.