Search code examples
pythonimage-processingjpeg

How to batch process images in a directory to create teaser-like thumbnails


I would like to run a script that goes through the jpgs in a directory one by one, takes a small square clip of the center of the image (100x100 pixels, for instance), and saves that square in a second directory as a new image.

Speed of execution is of no concern. Just looking for a way to get this done painlessly, preferably without needing to install anything I don't already have, and with a tool or language I sometimes use (preferably Python or Javascript).

How would you go about such a task?


Solution

  • Here is a Python script that does what you want. You need to install Pillow first using the command pip install Pillow:

    from PIL import Image
    import os
    
    def crop_center(image, width, height):
        img_width, img_height = image.size
        left = (img_width - width) // 2
        top = (img_height - height) // 2
        right = (img_width + width) // 2
        bottom = (img_height + height) // 2
        return image.crop((left, top, right, bottom))
    
    def process_images(input_dir, output_dir):
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
    
        for filename in os.listdir(input_dir):
            if filename.endswith('.jpg'):
                input_path = os.path.join(input_dir, filename)
                output_path = os.path.join(output_dir, filename)
                with Image.open(input_path) as img:
                    cropped_img = crop_center(img, 100, 100)
                    cropped_img.save(output_path)
    
    if __name__ == "__main__":
        input_directory = "/path/to/input/directory"  # Update this to your input directory
        output_directory = "/path/to/output/directory"  # Update this to your output directory
        process_images(input_directory, output_directory)
    

    the process_images() function runs through all the images in the given input_dir folder, applies the crop_center() function to each image and saves it to the given output_dir folder (if this folder doesn't exits, it's created).

    You can change the size of the crop by modifying the width and height parameters passed to the crop_center function call (I've set them both at 100 as per your example).