Pillow is a powerful library in Python for image processing, built as a fork of the Python Imaging Library (PIL).
With Pillow, you can perform a variety of operations like loading, editing, and saving images.
In this tutorial, we’ll cover:
1. Installing Pillow
To install Pillow, use pip
:
pip install pillow
2. Loading and Displaying Images
The Image
module is used to load and display images.
Example: Load and Display an Image
from PIL import Image
# Open an image file
image = Image.open("example.jpg")
# Display the image
image.show()
# Print basic image details
print(f"Format: {image.format}, Size: {image.size}, Mode: {image.mode}")
3. Basic Image Operations
3.1 Resizing an Image
image_resized = image.resize((200, 200))
image_resized.show()
3.2 Cropping an Image
# Define the box (left, upper, right, lower)
box = (50, 50, 200, 200)
cropped_image = image.crop(box)
cropped_image.show()
3.3 Rotating and Flipping an Image
rotated_image = image.rotate(45) # Rotate 45 degrees
rotated_image.show()
flipped_image = image.transpose(Image.FLIP_LEFT_RIGHT) # Flip horizontally
flipped_image.show()
4. Image Transformations
4.1 Converting to Grayscale
grayscale_image = image.convert("L")
grayscale_image.show()
4.2 Thumbnail Creation
The thumbnail
method preserves the aspect ratio.
thumbnail_image = image.copy()
thumbnail_image.thumbnail((100, 100))
thumbnail_image.show()
5. Adding Text and Drawing Shapes
Use the ImageDraw
module for drawing and adding text.
Example: Draw Shapes and Add Text
from PIL import ImageDraw, ImageFont
# Create a drawing object
draw = ImageDraw.Draw(image)
# Draw a rectangle
draw.rectangle((50, 50, 200, 200), outline="red", width=5)
# Draw a circle
draw.ellipse((300, 300, 400, 400), fill="blue", outline="white")
# Add text
font = ImageFont.truetype("arial.ttf", size=24) # Specify font and size
draw.text((50, 10), "Hello, Pillow!", fill="green", font=font)
image.show()
6. Working with Image Filters
The ImageFilter
module provides several built-in filters.
Example: Applying Filters
from PIL import ImageFilter
# Apply a blur filter
blurred_image = image.filter(ImageFilter.BLUR)
blurred_image.show()
# Apply a sharpen filter
sharpened_image = image.filter(ImageFilter.SHARPEN)
sharpened_image.show()
# Apply an edge enhancement filter
edges_image = image.filter(ImageFilter.EDGE_ENHANCE)
edges_image.show()
7. Saving Images
You can save images in different formats using the save
method.
Example: Save an Image
# Save as PNG
image.save("output_image.png", "PNG")
# Save with quality (for JPEGs)
image.save("output_image.jpg", "JPEG", quality=90)
Practical Examples
Example 1: Batch Image Resizing
Resize multiple images in a directory to a fixed size.
import os
from PIL import Image
input_folder = "input_images"
output_folder = "output_images"
os.makedirs(output_folder, exist_ok=True)
for filename in os.listdir(input_folder):
if filename.endswith(".jpg"):
img = Image.open(os.path.join(input_folder, filename))
img_resized = img.resize((300, 300))
img_resized.save(os.path.join(output_folder, filename))
print(f"Resized and saved: {filename}")
Example 2: Creating an Image Collage
Combine multiple images into a grid.
from PIL import Image
def create_collage(image_files, grid_size, output_file):
images = [Image.open(img).resize((100, 100)) for img in image_files]
# Create a blank image for the collage
collage = Image.new("RGB", (grid_size[0] * 100, grid_size[1] * 100))
for index, img in enumerate(images):
x = (index % grid_size[0]) * 100
y = (index // grid_size[0]) * 100
collage.paste(img, (x, y))
collage.save(output_file)
collage.show()
# Example usage
image_files = ["img1.jpg", "img2.jpg", "img3.jpg", "img4.jpg"]
create_collage(image_files, (2, 2), "collage.jpg")
Example 3: Watermarking an Image
Add a semi-transparent watermark to an image.
from PIL import Image, ImageDraw, ImageFont
def add_watermark(input_image, watermark_text, output_image):
img = Image.open(input_image).convert("RGBA")
# Create a transparent overlay
txt = Image.new("RGBA", img.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(txt)
font = ImageFont.truetype("arial.ttf", 40)
# Add text in the bottom-right corner
text_width, text_height = draw.textsize(watermark_text, font=font)
position = (img.size[0] - text_width - 10, img.size[1] - text_height - 10)
draw.text(position, watermark_text, fill=(255, 255, 255, 128), font=font)
# Combine the image with the watermark
watermarked = Image.alpha_composite(img, txt)
watermarked.save(output_image)
watermarked.show()
# Example usage
add_watermark("example.jpg", "Watermark Text", "watermarked_image.png")
Conclusion
Pillow is an essential library for image processing in Python. Whether you need to resize images, apply filters, or create collages, Pillow makes it simple and efficient.