@@ -18,59 +18,61 @@ def crop_to_ratio(img, target_ratio):
1818 top = (height - new_height ) // 2
1919 return img .crop ((0 , top , width , top + new_height ))
2020
21+
2122def process_image (file_path , ratio , max_size , format = "webp" ):
2223 """Process and overwrite the original image: crop, resize, convert format."""
2324 try :
2425 with Image .open (file_path ) as img :
2526 # Crop to target ratio
2627 if ratio :
2728 img = crop_to_ratio (img , ratio )
28-
29+
2930 # Resize to max dimensions
3031 if max_size :
3132 img .thumbnail (max_size )
32-
33+
3334 # convert to webp if no transparency
3435 if format .lower () == "webp" and img .mode != "RGBA" :
3536 file_path = os .path .splitext (file_path )[0 ] + ".webp"
3637 img .save (file_path , "webp" , optimize = True , quality = 85 )
3738 else :
3839 img .save (file_path , optimize = True )
39-
40+
4041 print (f"✅ Overwritten: { file_path } " )
4142 except Exception as e :
4243 print (f"❌ Failed { file_path } : { str (e )} " )
4344
45+
4446def main ():
45- folder = "assets/images"
46-
47+ folder = "assets/images"
48+
4749 # Rules for image types
4850 rules = [
4951 {
5052 "suffix" : ["banner" , "header" ],
51- "ratio" : 16 / 9 ,
53+ "ratio" : 16 / 9 ,
5254 "max_size" : (1920 , 1080 ), # Min size enforced via cropping
53- "format" : "webp"
55+ "format" : "webp" ,
5456 },
5557 {
5658 "suffix" : ["thumb" , "profile" ],
57- "ratio" : 1 / 1 ,
59+ "ratio" : 1 / 1 ,
5860 "max_size" : (800 , 800 ),
59- "format" : "webp"
60- }
61+ "format" : "webp" ,
62+ },
6163 ]
6264
6365 for filename in os .listdir (folder ):
64- if filename .lower ().endswith ((' .jpg' , ' .jpeg' , ' .png' , ' .webp' )):
66+ if filename .lower ().endswith ((" .jpg" , " .jpeg" , " .png" , " .webp" )):
6567 file_path = os .path .join (folder , filename )
66-
68+
6769 # Apply first rule
6870 matched_rule = None
6971 for rule in rules :
7072 if any (keyword in filename .lower () for keyword in rule ["suffix" ]):
7173 matched_rule = rule
7274 break
73-
75+
7476 # no cropping, resize to 800x600, convert to webp if no transparency
7577 if not matched_rule :
7678 with Image .open (file_path ) as img :
@@ -79,5 +81,6 @@ def main():
7981
8082 process_image (file_path , ** matched_rule )
8183
84+
8285if __name__ == "__main__" :
8386 main ()
0 commit comments