#! /usr/bin/env python3 import argparse import os from PIL import Image, ImageOps def add_border(image_path: str, desired_ratio: float, output_file: str) -> None: img = Image.open(image_path) width, height = img.size if width / height < desired_ratio: new_width = int(height * desired_ratio) border_width = (new_width - width) // 2 border = border_width, 0 else: new_height = int(width / desired_ratio) border_height = (new_height - height) // 2 border = 0, border_height ImageOps.expand(img, border=border, fill="black").save(output_file) def get_aspect_ratio(image_path: str) -> float: width, height = Image.open(image_path).size return width / height def main(): parser = argparse.ArgumentParser( description="Add black border to images to match a ratio." ) parser.add_argument( "reference", help="The image file from which to take the target aspect ratio." ) parser.add_argument("images", nargs="+", help="List of image files to process.") parser.add_argument( "-o", "--output", dest="output", required=True, help="The output folder." ) args = parser.parse_args() ratio = get_aspect_ratio(args.reference) print(f"Target ratio is: {ratio}") for img_path in args.images: print(f"Processing file {img_path}") add_border( img_path, ratio, os.path.join(args.output, os.path.basename(img_path)) ) if __name__ == "__main__": main()