Python: How to Split Images if the Height is too Large

In this post, I’m gonna show you how to split images if the height is larger than 16000 pixels in Python within the specified directory and its subdirectories.

To create a script that automatically splits an image vertically if it’s a PNG larger than 16000 pixels in height and then saves it as WebP, you can use Python with the Pillow (PIL Fork) and WebP libraries. This script will:

  1. Check if the image is a PNG.
  2. Check the image height.
  3. If the height is greater than 16000 pixels, split the image vertically.
  4. Save each part as WebP.

Here’s a step-by-step guide to achieving this:

Step 1: Install Required Libraries

First, you need to install Pillow and WebP libraries for Python. You can do this via pip:

pip install Pillow webp

Step 2: Python Script to Process the Image

Create a Python script (split_and_convert.py) with the following content:

import os
from PIL import Image
import errno

def split_and_convert_image(image_path):
    # Load the image
    try:
        img = Image.open(image_path)
    except IOError:
        print(f"Error opening image: {image_path}")
        return False

    img_format = img.format

    # Initialize a flag to indicate successful processing
    processed_successfully = False

    # Check if PNG and height is greater than 16000 pixels
    if img_format == 'PNG' and img.height > 16000:
        # Calculate the number of splits required
        num_splits = img.height // 16000
        if img.height % 16000 != 0:
            num_splits += 1

        # Split the image and save each part
        for i in range(num_splits):
            # Define the cropping box
            top = i * 16000
            bottom = min((i + 1) * 16000, img.height)
            cropped_img = img.crop((0, top, img.width, bottom))
            
            # Convert to WebP and save
            save_path = f"{os.path.splitext(image_path)[0]}_part_{i}.webp"
            cropped_img.save(save_path, format='WEBP', quality=90)
            print(f"Saved: {save_path}")
            processed_successfully = True

    # If the image was processed successfully, delete the original image
    if processed_successfully:
        try:
            os.remove(image_path)
            print(f"Deleted original image: {image_path}")
        except OSError as e:
            # Provide error message if the file couldn't be deleted
            if e.errno != errno.ENOENT:  # errno.ENOENT = no such file or directory
                print(f"Error deleting file {image_path}: {e.strerror}")
        return True
    return False

def find_and_process_images(start_dir):
    for root, dirs, files in os.walk(start_dir):
        for file in files:
            if file.lower().endswith(".png"):
                image_path = os.path.join(root, file)
                print(f"Processing {image_path}...")
                split_and_convert_image(image_path)

if __name__ == "__main__":
    start_dir = 'path/to/start/directory'  # Change this to your starting directory
    find_and_process_images(start_dir)

How The Script Works:

  • find_and_process_images function:
    • Recursively walks through the starting directory and its subdirectories.
    • Checks each file to see if it ends with .png. If so, it processes the file with split_and_convert_image.
  • split_and_convert_image function:
    • This function remains largely the same as before, taking an image path, checking if the image is a large PNG, splitting it if necessary, and saving each part as WebP.

Step 3: Running the Updated Script

Run your script with Python:

python split_and_convert.py

Make sure to change 'path/to/start/directory' in the script to the actual path of your starting directory.

Additional Notes:

  • Backup: Before running a script that deletes files, it’s wise to create backups of your data, especially if you’re processing important images.
  • Testing: Test the script on a few sample images or a copy of your dataset to ensure it works as expected before running it on all your images.
  • Performance: This script might take a while to execute depending on the number of images and their sizes.
  • File System Permissions: Ensure the script has the necessary permissions to read and write files in the directories it’s processing.
  • Error Handling: Consider adding error handling around file and image operations to handle any issues with specific files gracefully.

The script from the above will process all PNG images larger than 16,000 pixels in height found within the specified directory and its subdirectories. Each processed image will be split (if necessary), converted to WebP format, and the original PNG file will be deleted.

Recent Articles

Related Stories

Stay on op - Ge the daily news in your inbox