@@ -18,59 +18,61 @@ def crop_to_ratio(img, target_ratio):
18
18
top = (height - new_height ) // 2
19
19
return img .crop ((0 , top , width , top + new_height ))
20
20
21
+
21
22
def process_image (file_path , ratio , max_size , format = "webp" ):
22
23
"""Process and overwrite the original image: crop, resize, convert format."""
23
24
try :
24
25
with Image .open (file_path ) as img :
25
26
# Crop to target ratio
26
27
if ratio :
27
28
img = crop_to_ratio (img , ratio )
28
-
29
+
29
30
# Resize to max dimensions
30
31
if max_size :
31
32
img .thumbnail (max_size )
32
-
33
+
33
34
# convert to webp if no transparency
34
35
if format .lower () == "webp" and img .mode != "RGBA" :
35
36
file_path = os .path .splitext (file_path )[0 ] + ".webp"
36
37
img .save (file_path , "webp" , optimize = True , quality = 85 )
37
38
else :
38
39
img .save (file_path , optimize = True )
39
-
40
+
40
41
print (f"✅ Overwritten: { file_path } " )
41
42
except Exception as e :
42
43
print (f"❌ Failed { file_path } : { str (e )} " )
43
44
45
+
44
46
def main ():
45
- folder = "assets/images"
46
-
47
+ folder = "assets/images"
48
+
47
49
# Rules for image types
48
50
rules = [
49
51
{
50
52
"suffix" : ["banner" , "header" ],
51
- "ratio" : 16 / 9 ,
53
+ "ratio" : 16 / 9 ,
52
54
"max_size" : (1920 , 1080 ), # Min size enforced via cropping
53
- "format" : "webp"
55
+ "format" : "webp" ,
54
56
},
55
57
{
56
58
"suffix" : ["thumb" , "profile" ],
57
- "ratio" : 1 / 1 ,
59
+ "ratio" : 1 / 1 ,
58
60
"max_size" : (800 , 800 ),
59
- "format" : "webp"
60
- }
61
+ "format" : "webp" ,
62
+ },
61
63
]
62
64
63
65
for filename in os .listdir (folder ):
64
- if filename .lower ().endswith ((' .jpg' , ' .jpeg' , ' .png' , ' .webp' )):
66
+ if filename .lower ().endswith ((" .jpg" , " .jpeg" , " .png" , " .webp" )):
65
67
file_path = os .path .join (folder , filename )
66
-
68
+
67
69
# Apply first rule
68
70
matched_rule = None
69
71
for rule in rules :
70
72
if any (keyword in filename .lower () for keyword in rule ["suffix" ]):
71
73
matched_rule = rule
72
74
break
73
-
75
+
74
76
# no cropping, resize to 800x600, convert to webp if no transparency
75
77
if not matched_rule :
76
78
with Image .open (file_path ) as img :
@@ -79,5 +81,6 @@ def main():
79
81
80
82
process_image (file_path , ** matched_rule )
81
83
84
+
82
85
if __name__ == "__main__" :
83
86
main ()
0 commit comments