Updated: 21 dec 2025
This code shrinks the file size of JPG images
from PIL import Image
import os
root_directory = 'C:/test'
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
find_and_compress_images(root_directory)