Resizing images is one of the most common tasks in image processing. Pillow (PIL fork) makes resizing straightforward while allowing you to maintain quality, preserve the aspect ratio, or customize the size.
In this tutorial, we will cover:
1. Installing Pillow
Install Pillow using pip:
pip install pillow
2. Resizing Images to Exact Dimensions
To resize an image to exact dimensions, use the resize() method.
Example: Simple Resizing
from PIL import Image # Open an image file image = Image.open("example.jpg") # Resize the image to 300x300 pixels resized_image = image.resize((300, 300)) # Save the resized image resized_image.save("resized_image.jpg") # Show the resized image resized_image.show()
Explanation
- The resize() method takes a tuple (width, height) as its argument.
- The aspect ratio is not preserved; the image may look distorted.
3. Resizing While Preserving Aspect Ratio
To resize while maintaining the aspect ratio, calculate the new dimensions based on the original aspect ratio.
Example: Resizing While Maintaining Aspect Ratio
from PIL import Image def resize_with_aspect_ratio(image_path, base_width): # Open the image image = Image.open(image_path) # Calculate the new height maintaining the aspect ratio w_percent = base_width / float(image.size[0]) new_height = int(float(image.size[1]) * w_percent) # Resize the image resized_image = image.resize((base_width, new_height), Image.Resampling.LANCZOS) # Save and show the image resized_image.save("resized_aspect_ratio.jpg") resized_image.show() # Example usage resize_with_aspect_ratio("example.jpg", 400)
Explanation
- The base_width is fixed, and the height is calculated proportionally.
- The Image.Resampling.LANCZOS filter ensures high-quality resizing.
4. Creating Thumbnails
The thumbnail() method creates a resized version while maintaining the aspect ratio and ensuring the image fits within the specified dimensions.
Example: Creating a Thumbnail
from PIL import Image # Open an image file image = Image.open("example.jpg") # Create a thumbnail with maximum dimensions of 150x150 image.thumbnail((150, 150)) # Save and show the thumbnail image.save("thumbnail.jpg") image.show()
Explanation
- The thumbnail() method resizes the image in-place.
- It automatically maintains the aspect ratio, ensuring the image fits within the given dimensions.
5. Batch Resizing Multiple Images
You can resize multiple images in a directory to a fixed size.
Example: Batch Resizing
import os from PIL import Image def batch_resize(input_folder, output_folder, size): os.makedirs(output_folder, exist_ok=True) for filename in os.listdir(input_folder): if filename.endswith((".jpg", ".png", ".jpeg")): img = Image.open(os.path.join(input_folder, filename)) img_resized = img.resize(size, Image.Resampling.LANCZOS) img_resized.save(os.path.join(output_folder, filename)) print(f"Resized and saved: {filename}") # Example usage batch_resize("input_images", "output_images", (300, 300))
Explanation
- input_folder is the directory with original images.
- output_folder is where resized images are saved.
- The size tuple specifies the new dimensions for all images.
6. Resizing with Advanced Options
6.1 Using Different Resampling Filters
Pillow provides several resampling filters for resizing:
- Image.Resampling.NEAREST (fast but low quality)
- Image.Resampling.BOX
- Image.Resampling.BILINEAR
- Image.Resampling.HAMMING
- Image.Resampling.BICUBIC
- Image.Resampling.LANCZOS (best quality)
from PIL import Image # Open an image image = Image.open("example.jpg") # Resize using a specific filter resized_image = image.resize((400, 400), Image.Resampling.BICUBIC) # Save and show the resized image resized_image.save("resized_bicubic.jpg") resized_image.show()
6.2 Adding Padding to Avoid Distortion
If you want to resize without distortion but need the output to be an exact size, add padding.
from PIL import Image, ImageOps def resize_with_padding(image_path, output_size): image = Image.open(image_path) padded_image = ImageOps.pad(image, output_size, color="black", centering=(0.5, 0.5)) padded_image.save("padded_image.jpg") padded_image.show() # Example usage resize_with_padding("example.jpg", (400, 400))
7. Examples and Use Cases
7.1 Resizing for Social Media
Resize images to fit social media platform requirements.
resize_with_aspect_ratio("example.jpg", 1080) # Instagram post width
7.2 Generating Thumbnails for a Gallery
Use thumbnail() to create uniform-sized thumbnails for a photo gallery.
batch_resize("photos", "thumbnails", (150, 150))
7.3 High-Quality Resizing for Print
For print-quality resizing, use a larger dpi setting and Image.Resampling.LANCZOS.
Conclusion
Resizing images with Pillow is both simple and powerful. You can resize to exact dimensions, maintain aspect ratios, or add padding to fit your needs.
Batch resizing and thumbnails are great for large-scale tasks like managing photo collections or generating website content.