import sys from pathlib import Path from PIL import Image, ImageOps, UnidentifiedImageError MAX_INPUT_PIXELS = 20_000_000 def main(): input_path = Path(sys.argv[1]) output_dir = Path(sys.argv[2]) try: with Image.open(input_path) as source: if source.width * source.height > MAX_INPUT_PIXELS: return 20 source.load() img = source.convert("RGB") crop = ImageOps.fit( img, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5) ) crop.save( output_dir / "crop.jpg", format="JPEG", quality=85 ) img.save( output_dir / "optimized.webp", format="WEBP", quality=80, method=6 ) img.thumbnail((256, 256)) img.save( output_dir / "thumbnail.jpg", format="JPEG", quality=85 ) except ( UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError, ): return 21 return 0 if __name__ == "__main__": sys.exit(main())