Figshrinker#
This page reuses BSD 3-Clause License content from TeachBooks (2024). Find out more here.
# shrink file size of JPG
# file zoekt naar jpg bestanden en comprimeert deze tot een gewenste formaat.
from PIL import Image
import os
def compress_image(file_path, output_quality=50):
""" Compress the image by changing its quality. """
picture = Image.open(file_path)
# You can also resize the image if needed using picture.resize()
picture.save(file_path, "JPEG", optimize=True, quality=output_quality)
def find_and_compress_images(directory, max_size=1.5*1024*1024):
""" Find all jpg files exceeding max_size and compress them. """
for root, dirs, files in os.walk(directory):
for file in files:
if file.lower().endswith(".jpg"):
full_path = os.path.join(root, file)
if os.path.getsize(full_path) > max_size:
print(f"Compressing: {full_path}")
compress_image(full_path)
# Specify the root directory to start from
root_directory = 'I:/Book/2023'
find_and_compress_images(root_directory)