Python 3 Pillow Script to Resize All Images inside Directory or Folder Full Project For Beginners

 

 

pip install pillow

 

 

 

main.py

 

 

#! /usr/bin/python3
import sys
import os
import glob
import argparse
import imghdr
try:
    from PIL import Image
except ImportError:
    from pip._internal import main as pip
    pip(['install', '--user', 'Pillow'])
    from PIL import Image
try:
    from colorama import Fore, Style
except ImportError:
    from pip._internal import main as pip
    pip(['install', '--user', 'colorama'])
    from colorama import Fore, Style

def main():
    parser = argparse.ArgumentParser(description='Resizes all images in a directory, preserving their aspect ratio.')
    parser.add_argument('--width', type=int, required=True, help='The target width of the resized images.')
    parser.add_argument('--source', type=str, nargs='?', default='.', help='The source directory containing images to be processed. If omitted, defaults to the directory from which the script was invoked.')
    parser.add_argument('--output', type=str, nargs='?', help='The output directory for the resized images.')
    parser.add_argument('--tail', type=str, help='A string to append to all resized images, after the original name but before the file extension (e.g., "-thumbnail"). By default, this will be w, where w is whatever width you specified.')
    args = parser.parse_args()

    width = args.width
    source_dir = args.source
    output_dir = args.output if args.output else source_dir
    tail = args.tail if args.tail else f'-{width}'

    # Make sure the output path actually exists (for when we create and save images later)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # Get all the image files in the source dir
    files = filter(os.path.isfile, os.listdir(source_dir))
    image_files = [file for file in files if imghdr.what(file)]

    for image_file in image_files:
        fully_qualified_image_path = os.path.join(source_dir, image_file)
        image_name, image_extension = os.path.splitext(image_file)
        print(Fore.YELLOW + 'Processing: ' + Style.RESET_ALL + fully_qualified_image_path)

        # Skip files previously generated by the script. Mainly a precaution if the output dir is the same as the source dir.
        # Otherwise, each successive invocation of this script will generate a new file for previously created images.
        if image_name.endswith(tail):
            print(Fore.YELLOW + 'Skipping previously resized image: ' + Style.RESET_ALL + fully_qualified_image_path)
            continue
    
        try:
            img = Image.open(fully_qualified_image_path)
            img.thumbnail((width, width), Image.ANTIALIAS)
            # final_image = img.convert('RGB')
            final_image = img

            target_file_name = os.path.join(output_dir, image_name) + tail + image_extension
            final_image.save(target_file_name)
            print(Fore.GREEN + f'Successfully generated resized image ({width}x{final_image.size[1]}): ' + Style.RESET_ALL + target_file_name)                          
        
        except Exception:
            print(Fore.RED + 'Unable to process image: ' + Style.RESET_ALL + fully_qualified_image_path)
                
if __name__ == "__main__":
    main()

Leave a Reply