Python Snippets

Automatic Image Resizer with Aspect Ratio Preservation

This Python script automatically resizes images while maintaining their aspect ratio, making it perfect for preparing images for web use or creating thumbnails. It’s particularly useful when you need to process multiple images at once with consistent sizing rules.

from PIL import Image
import os
import sys

def resize_image_with_aspect_ratio(input_path, output_path, target_width, target_height):
    """
    Resize an image while maintaining aspect ratio and add padding if needed.
    
    Args:
        input_path (str): Path to the input image
        output_path (str): Path to save the resized image
        target_width (int): Desired width
        target_height (int): Desired height
    """
    with Image.open(input_path) as img:
        # Calculate aspect ratios
        img_ratio = img.width / img.height
        target_ratio = target_width / target_height
        
        # Determine new dimensions based on aspect ratio
        if img_ratio > target_ratio:
            # Image is wider than target
            new_width = target_width
            new_height = int(target_width / img_ratio)
        else:
            # Image is taller than target
            new_height = target_height
            new_width = int(target_height * img_ratio)
        
        # Resize the image with high-quality resampling
        resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
        
        # Create a new image with target dimensions and paste resized image
        final_img = Image.new('RGB', (target_width, target_height), (255, 255, 255))  # White background
        paste_x = (target_width - new_width) // 2
        paste_y = (target_height - new_height) // 2
        final_img.paste(resized_img, (paste_x, paste_y))
        
        # Save the final image
        final_img.save(output_path, quality=95)

def batch_resize_images(input_dir, output_dir, width, height):
    """
    Resize all images in a directory.
    
    Args:
        input_dir (str): Directory containing input images
        output_dir (str): Directory to save resized images
        width (int): Target width
        height (int): Target height
    """
    # Supported image formats
    supported_formats = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp')
    
    # Create output directory if it doesn't exist
    os.makedirs(output_dir, exist_ok=True)
    
    # Process each image in the input directory
    for filename in os.listdir(input_dir):
        if filename.lower().endswith(supported_formats):
            input_path = os.path.join(input_dir, filename)
            output_path = os.path.join(output_dir, filename)
            try:
                resize_image_with_aspect_ratio(input_path, output_path, width, height)
                print(f"Resized: {filename}")
            except Exception as e:
                print(f"Error processing {filename}: {e}")

# Example usage
if __name__ == "__main__":
    # Single image example
    # resize_image_with_aspect_ratio("input.jpg", "output.jpg", 800, 600)
    
    # Batch processing example
    batch_resize_images("input_images", "resized_images", 1200, 800)

Explanation

This script provides two main functions for resizing images intelligently:

  1. resize_image_with_aspect_ratio(): Resizes a single image while maintaining its proportions. Instead of stretching or cropping, it calculates the correct dimensions and adds padding (white bars) to fill the target area. This preserves the entire image while fitting within specified dimensions.

  2. batch_resize_images(): Processes multiple images in a directory, applying the same resizing parameters to all supported image files.

The script handles aspect ratio preservation by:

Benefits

How to Run

  1. Install the required dependency:
    pip install Pillow
    
  2. Prepare your files:
    • Create an input_images directory with your source images
    • Adjust the target dimensions in the script (currently 1200x800)
  3. Run the script:
    python image_resizer.py
    
  4. Find your resized images in the resized_images directory

For single image processing, uncomment the first example in the if __name__ == "__main__": block and comment out the batch processing line.

The script is ideal for preparing images for websites, creating uniform thumbnails, or reducing file sizes while maintaining visual quality.