Created
April 22, 2024 21:31
-
-
Save wassef911/7face6443c929f96d7959592d87585ea to your computer and use it in GitHub Desktop.
useful to run against a media directory to save space... (make sure to experiment with quality kwarg!)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from PIL import Image | |
def compress_png_in_place(folder_path): | |
""" | |
Recursively finds all PNG files in the specified directory, compresses them, and saves them in place. | |
Args: | |
folder_path (str): The path to the directory where to start searching and compressing PNG files. | |
""" | |
for root, dirs, files in os.walk(folder_path): | |
for file in files: | |
if file.lower().endswith((".png", ".jpeg", ".jpg")): | |
full_path = os.path.join(root, file) | |
print(f"Compressing {full_path}", os.path.getsize(full_path)) | |
try: | |
compress_image(full_path) | |
except Exception as e: | |
print(f"Failed to compress {full_path}: {e}") | |
continue | |
print("Compressed =", os.path.getsize(full_path)) | |
def compress_image(image_path): | |
""" | |
Compresses a PNG image and overwrites the original image file. | |
Args: | |
image_path (str): The path to the image to be compressed. | |
""" | |
with Image.open(image_path) as img: | |
img.save(image_path, optimize=True, quality=75) | |
if __name__ == "__main__": | |
folder_path = ( | |
"/opt/app/media" | |
) | |
all_png_files = compress_png_in_place(folder_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment