-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert_thumbnails.py
More file actions
42 lines (33 loc) · 1.42 KB
/
convert_thumbnails.py
File metadata and controls
42 lines (33 loc) · 1.42 KB
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
from PIL import Image
# Settings
TARGET_DIR = "projects"
TARGET_NAME = "thumbnail.jpg"
OUTPUT_NAME = "thumbnail.webp"
MAX_SIZE_KB = 50
QUALITY_STEP = 5
REMOVE_ORIGINAL = False # Set to True to delete .jpg after conversion
def convert_and_compress_to_webp(input_path, output_path, max_size_kb):
img = Image.open(input_path).convert("RGB")
quality = 95
while quality >= 10:
img.save(output_path, format="WEBP", quality=quality)
size_kb = os.path.getsize(output_path) / 1024
if size_kb <= max_size_kb:
print(f"✔ Converted {input_path} → {output_path} ({int(size_kb)} KB @ quality={quality})")
return
quality -= QUALITY_STEP
print(f"⚠ Couldn't compress {input_path} below {max_size_kb} KB")
def process_directory(base_dir):
for root, dirs, files in os.walk(base_dir):
for filename in files:
if filename.lower().endswith(".jpg") and "thumbnail" in filename.lower():
input_path = os.path.join(root, filename)
output_name = os.path.splitext(filename)[0] + ".webp"
output_path = os.path.join(root, output_name)
convert_and_compress_to_webp(input_path, output_path, MAX_SIZE_KB)
if REMOVE_ORIGINAL:
os.remove(input_path)
print(f"Removed original: {input_path}")
if __name__ == "__main__":
process_directory(TARGET_DIR)