@@ -72,33 +72,32 @@ def resize_uploaded_image(
7272 return path # already within bounds – no work needed
7373
7474 # thumbnail() shrinks in-place preserving aspect ratio, never upscales.
75- img = opened_img .copy ()
76-
77- img .thumbnail ((max_width , max_height ), Image .Resampling .LANCZOS )
78-
79- # Persist transparency for PNG/WebP; flatten to RGB for JPEG.
80- if ext in (".jpg" , ".jpeg" ):
81- if img .mode in ("RGBA" , "P" , "LA" ):
82- img = img .convert ("RGB" )
83- suffix , fmt , save_kw = ".jpg" , "JPEG" , {"quality" : 85 , "optimize" : True }
84- elif ext == ".webp" :
85- suffix , fmt , save_kw = ".webp" , "WEBP" , {"quality" : 85 }
86- else :
87- # Preserve original format and extension so downstream format
88- # detection (e.g. detect_ext_token) is not misled by a .png suffix.
89- fmt = _PIL_FORMAT_MAP .get (ext , "PNG" )
90- suffix = ext if fmt != "PNG" else ".png"
91- save_kw = {}
92-
93- fd , tmp_path = tempfile .mkstemp (suffix = suffix )
94- os .close (fd )
95- img .save (tmp_path , format = fmt , ** save_kw )
96-
97- log .debug (
98- "Resized upload %s from %dx%d → %dx%d (saved to %s)" ,
99- path , orig_w , orig_h , img .width , img .height , tmp_path ,
100- )
101- return tmp_path
75+ # Do everything inside the with-block to avoid a full-size copy.
76+ opened_img .thumbnail ((max_width , max_height ), Image .Resampling .LANCZOS )
77+
78+ # Persist transparency for PNG/WebP; flatten to RGB for JPEG.
79+ if ext in (".jpg" , ".jpeg" ):
80+ save_img = opened_img .convert ("RGB" ) if opened_img .mode in ("RGBA" , "P" , "LA" ) else opened_img
81+ suffix , fmt , save_kw = ".jpg" , "JPEG" , {"quality" : 85 , "optimize" : True }
82+ elif ext == ".webp" :
83+ save_img , suffix , fmt , save_kw = opened_img , ".webp" , "WEBP" , {"quality" : 85 }
84+ else :
85+ # Preserve original format and extension so downstream format
86+ # detection (e.g. detect_ext_token) is not misled by a .png suffix.
87+ save_img = opened_img
88+ fmt = _PIL_FORMAT_MAP .get (ext , "PNG" )
89+ suffix = ext if fmt != "PNG" else ".png"
90+ save_kw = {}
91+
92+ fd , tmp_path = tempfile .mkstemp (suffix = suffix )
93+ os .close (fd )
94+ save_img .save (tmp_path , format = fmt , ** save_kw )
95+
96+ log .debug (
97+ "Resized upload %s from %dx%d → %dx%d (saved to %s)" ,
98+ path , orig_w , orig_h , save_img .width , save_img .height , tmp_path ,
99+ )
100+ return tmp_path
102101
103102 except Exception :
104103 log .warning ("resize_uploaded_image: could not resize %s; using original" , path , exc_info = True )
0 commit comments