The Pillow library (formerly known as PIL – Python Imaging Library) is a powerful tool for image processing in Python.
One of its useful features is the ability to create thumbnails, which helps in reducing image size while maintaining aspect ratio.
This tutorial covers:
Installing Pillow
Loading and displaying images
Creating thumbnails while preserving aspect ratio
Customizing thumbnail size and quality
Batch processing multiple images
By the end of this guide, you’ll be able to efficiently generate thumbnails using Python.
Installing Pillow
To work with images in Python, install Pillow using pip:
pip install pillow
Once installed, you can verify the installation by importing the module:
from PIL import Image
Loading and Displaying an Image
Before creating a thumbnail, let's learn how to load and display an image using Pillow.
Example: Open and Display an Image
from PIL import Image # Open an image file img = Image.open("example.jpg") # Show the image img.show()
This code opens an image file named example.jpg and displays it using the default image viewer.
Creating a Simple Thumbnail
To create a thumbnail, we use the thumbnail() method, which resizes the image while maintaining its aspect ratio.
Example: Generate a Thumbnail
from PIL import Image # Open an image file img = Image.open("example.jpg") # Define thumbnail size (width, height) thumbnail_size = (200, 200) # Create thumbnail (maintains aspect ratio) img.thumbnail(thumbnail_size) # Save the thumbnail img.save("example_thumbnail.jpg") # Show the thumbnail img.show()
How it Works
- thumbnail((200, 200)) resizes the image so that neither width nor height exceeds 200px.
- The aspect ratio is preserved, so the thumbnail might not be exactly 200×200 but fits within that size.
- The thumbnail is saved as “example_thumbnail.jpg”.
Best for: Generating responsive images for web applications.
Customizing Thumbnail Quality
By default, Pillow compresses images while saving. You can improve image quality by specifying the JPEG quality.
Example: Saving Thumbnail with Higher Quality
img.save("example_thumbnail.jpg", quality=95, optimize=True)
Options Explained
- quality=95: Controls compression (default is 75, range 1-100).
- optimize=True: Reduces file size without losing much quality.
Use this when saving thumbnails for high-resolution displays.
Cropping Thumbnails to Exact Size
If you want an exact square thumbnail (e.g., 200x200px), you need to crop the image instead of using thumbnail().
Example: Creating a Fixed-Size Square Thumbnail
from PIL import Image # Open image img = Image.open("example.jpg") # Define target size thumb_size = (200, 200) # Get original width and height width, height = img.size # Calculate cropping box for a centered crop left = (width - min(width, height)) / 2 top = (height - min(width, height)) / 2 right = (width + min(width, height)) / 2 bottom = (height + min(width, height)) / 2 # Crop to a square img_cropped = img.crop((left, top, right, bottom)) # Resize to target size img_cropped = img_cropped.resize(thumb_size) # Save the square thumbnail img_cropped.save("example_square_thumbnail.jpg") # Show the final image img_cropped.show()
How it Works
- Crops the centered portion of the image to make it square.
- Resizes the cropped image to exact dimensions (200x200px).
Useful for profile pictures, product thumbnails, or social media images.
Converting to Different Formats
You may need to save thumbnails in different formats like PNG, JPEG, or WEBP.
Example: Save as PNG or WEBP
img.save("example_thumbnail.png", format="PNG") img.save("example_thumbnail.webp", format="WEBP", quality=90)
WEBP format is useful for websites as it provides smaller file sizes without much loss in quality.
Batch Processing Multiple Images
If you have multiple images in a folder, you can automate thumbnail generation.
Example: Creating Thumbnails for All Images in a Folder
import os from PIL import Image # Input and output directories input_folder = "images/" output_folder = "thumbnails/" # Thumbnail size thumbnail_size = (200, 200) # Ensure output folder exists os.makedirs(output_folder, exist_ok=True) # Process all images in the input folder for filename in os.listdir(input_folder): if filename.endswith((".jpg", ".jpeg", ".png", ".webp")): img_path = os.path.join(input_folder, filename) img = Image.open(img_path) # Create and save thumbnail img.thumbnail(thumbnail_size) img.save(os.path.join(output_folder, filename)) print(f"Thumbnail saved: {filename}") print("Batch processing complete!")
How it Works
- Loops through all .jpg, .jpeg, .png, .webp files in the folder.
- Generates thumbnails and saves them in the thumbnails/ directory.
Perfect for large-scale thumbnail processing!
Creating Watermarked Thumbnails
You can add a watermark to a thumbnail to protect your images.
Example: Adding a Watermark
from PIL import Image, ImageDraw, ImageFont # Open image img = Image.open("example.jpg") # Create thumbnail img.thumbnail((300, 300)) # Load font (use a TTF font) font = ImageFont.truetype("arial.ttf", 20) # Create draw object draw = ImageDraw.Draw(img) # Position for watermark text = "Sample" text_width, text_height = draw.textsize(text, font=font) position = (img.width - text_width - 10, img.height - text_height - 10) # Apply watermark draw.text(position, text, font=font, fill=(255, 255, 255, 128)) # Save image img.save("example_watermarked_thumbnail.jpg") # Show image img.show()
Great for branding and protecting content!
Summary
Feature | Method |
---|---|
Basic Thumbnail | thumbnail((width, height)) |
Higher Quality | save(quality=95, optimize=True) |
Exact Size Crop | crop((left, top, right, bottom)) |
Different Formats | save(format=”PNG”) |
Batch Processing | os.listdir() & thumbnail() |
Watermarking | ImageDraw.text() |
Conclusion
Using Pillow (PIL), we can resize, crop, and process images for thumbnails.
The thumbnail() method is efficient and maintains aspect ratio.
Automate thumbnail generation using batch processing.
Save in different formats (JPEG, PNG, WEBP) for flexibility.
Add watermarks for branding.
Now you can create thumbnails efficiently in Python! Let me know if you need any modifications or advanced techniques.