Created
August 9, 2024 07:41
-
-
Save OliverVea/6d6868442c06b3f94c277bae3dc35d0e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| from PIL import Image | |
| from pathlib import Path | |
| def compress_image(source: Path, destination: Path, quality=20): | |
| with Image.open(source) as image: | |
| rgb_image = image.convert('RGB') | |
| rgb_image.save(destination, quality=quality, optimize=True, format='JPEG') | |
| def compress_images(source_folder: Path, destination_folder: Path, globs: list[str], quality: int = 25): | |
| destination_folder.mkdir(exist_ok=True, parents=True) | |
| for glob in globs: | |
| for source in source_folder.glob(glob): | |
| destination = destination_folder / source.name | |
| destination = destination.with_suffix('.jpg') | |
| compress_image(source, destination, quality=quality) | |
| def clear_folder(folder: Path, globs: list[str]): | |
| for glob in globs: | |
| for file in folder.glob(glob): | |
| file.unlink() | |
| if __name__ == '__main__': | |
| root = Path(__file__).parent | |
| source_folder = root / 'raw' | |
| destination_folder = root / 'compressed' | |
| clear_folder(destination_folder, ['*.jpg', '*.jpeg', '*.png']) | |
| compress_images(source_folder, destination_folder, ['*.jpg', '*.jpeg', '*.png']) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment