1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import os import shutil from concurrent.futures import ThreadPoolExecutor from PIL import Image
input_folder = 'input_folder' output_folder = 'output_folder'
if not os.path.exists(output_folder): os.makedirs(output_folder)
file_names = [f for f in os.listdir(input_folder) if os.path.isfile(os.path.join(input_folder, f)) and any(f.endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif'])]
def process_image(file_name): input_file_path = os.path.join(input_folder, file_name) output_file_path = os.path.join(output_folder, file_name) with Image.open(input_file_path) as image: if image.format in ['JPEG', 'JPG', 'PNG']: compressed_image = image.copy() compressed_image.save(output_file_path, optimize=True, quality=25) while os.path.getsize(output_file_path) > 500 * 800: width, height = compressed_image.size new_width = int(width * 0.9) new_height = int(height * 0.9) compressed_image = compressed_image.resize((new_width, new_height)) compressed_image.save(output_file_path, optimize=True, quality=25)
with ThreadPoolExecutor() as executor: executor.map(process_image, file_names)
|