import os
from PIL import Image
import tinify
from concurrent.futures import ThreadPoolExecutor
input_folder = '/img'
whitelist = {'example1.jpg', 'important_image.png'}
quality = 75
def compress_image(img_path, quality):
"""
压缩单张图片并覆盖原文件。
:param img_path: 图片路径
:param quality: 压缩质量
"""
try:
img = Image.open(img_path)
img.save(img_path, optimize=True, quality=quality)
print(f"Compressed and saved in place: {img_path}")
except Exception as e:
print(f"Failed to compress {img_path}: {e}")
def compress_images_in_place(input_folder, whitelist=None, quality=75):
"""
使用 Pillow 压缩图片并覆盖原文件,支持白名单功能。使用多线程加速处理。
:param input_folder: 原始图片文件夹路径
:param whitelist: 白名单列表,包含不希望被压缩的图片文件名(可选)
:param quality: 压缩质量,默认75
"""
if whitelist is None:
whitelist = set()
with ThreadPoolExecutor() as executor:
futures = []
for root, dirs, files in os.walk(input_folder):
for file in files:
if file in whitelist:
print(f"Skipping (whitelisted): {file}")
continue
if file.lower().endswith(('.jpg', '.jpeg', '.png')):
img_path = os.path.join(root, file)
futures.append(executor.submit(compress_image, img_path, quality))
for future in futures:
future.result()
compress_images_in_place(input_folder, whitelist, quality)