compress_images
unknown
python
3 years ago
1.4 kB
13
Indexable
import os
from PIL import Image
def compress_images(directory, output_directory, quality=50):
# Create output directory if it doesn't exist
if not os.path.exists(output_directory):
os.makedirs(output_directory)
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
if os.path.isfile(file_path):
# Open the image
image = Image.open(file_path)
# Get the original file size
original_size = os.path.getsize(file_path)
print(f"Original file size: {original_size / (1024 * 1024):.2f} MB")
# Compress and save the image
compressed_image_path = os.path.join(output_directory, filename)
image.save(compressed_image_path, optimize=True, quality=quality)
# Get the compressed file size
compressed_size = os.path.getsize(compressed_image_path)
print(f"Compressed file size: {compressed_size / (1024 * 1024):.2f} MB")
# Close the image
image.close()
# Get the current directory of the script
script_directory = os.path.dirname(os.path.abspath(__file__))
# Create the output directory path
output_directory = os.path.join(script_directory, 'low_size_images')
# Compress images in the current directory and save them in the output directory
compress_images(script_directory, output_directory)
Editor is loading...