optimize.py (1008B)
1 import os 2 from PIL import Image 3 4 # Function to optimize images and strip EXIF data 5 def optimize_and_strip_exif(directory): 6 for root, _, files in os.walk(directory): 7 for filename in files: 8 if filename.lower().endswith(('.png', '.jpg', '.jpeg')): 9 image_path = os.path.join(root, filename) 10 try: 11 # Open the image 12 with Image.open(image_path) as img: 13 print(f"Optimized {image_path}") 14 data = list(img.getdata()) 15 image2 = Image.new(img.mode, img.size) 16 image2.putdata(data) 17 # Optimize the image for the web (compress) 18 image2.save(image_path, optimize=True, quality=85) 19 except Exception as e: 20 print(f"Error optimizing {image_path}: {str(e)}") 21 22 # Optimize images and strip EXIF data in the 'images' directory 23 optimize_and_strip_exif('images')