@@ -28,36 +28,58 @@ def get_bucket_name() -> str:
2828
2929
3030def resize_image (image_path , resized_path ):
31- with Image .open (image_path ) as image :
32- # Calculate the thumbnail size
33- width , height = image .size
34- max_width , max_height = MAX_DIMENSIONS
35- if width > max_width or height > max_height :
36- ratio = max (width / max_width , height / max_height )
37- width = int (width / ratio )
38- height = int (height / ratio )
39- size = width , height
40- # Generate the resized image
41- image .thumbnail (size )
42- image .save (resized_path )
43-
44-
45- def download_and_resize (bucket , key ) -> str :
31+ try :
32+ # Open the image using PIL
33+ with Image .open (image_path ) as image :
34+ # Calculate thumbnail size
35+ width , height = image .size
36+ max_width , max_height = MAX_DIMENSIONS
37+ if width > max_width or height > max_height :
38+ ratio = max (width / max_width , height / max_height )
39+ width = int (width / ratio )
40+ height = int (height / ratio )
41+ size = width , height
42+
43+ # Resize the image using thumbnail method
44+ image .thumbnail (size )
45+
46+ # Save the resized image
47+ image .save (resized_path )
48+ return True
49+ except Exception as e :
50+ print (f"Error resizing image: { e } " )
51+ return False
52+
53+
54+ def download_and_resize (bucket , key , target_bucket ) -> str :
4655 tmpkey = key .replace ("/" , "" )
4756 download_path = f"/tmp/{ uuid .uuid4 ()} { tmpkey } "
4857 upload_path = f"/tmp/resized-{ tmpkey } "
4958 s3 .download_file (bucket , key , download_path )
50- resize_image (download_path , upload_path )
51- return upload_path
59+ success = resize_image (download_path , upload_path )
60+ if success :
61+ s3 .upload_file (upload_path , target_bucket , key )
62+ return upload_path
63+ else :
64+ print (f"Failed to resize image: { key } " )
65+ return None
5266
5367
5468def handler (event , context ):
69+ print (f"Event received: { event } " )
5570 target_bucket = get_bucket_name ()
5671
5772 for record in event ["Records" ]:
5873 source_bucket = record ["s3" ]["bucket" ]["name" ]
5974 key = unquote_plus (record ["s3" ]["object" ]["key" ])
60- print (source_bucket , key )
75+ print (f"Processing { source_bucket } / { key } " )
6176
62- resized_path = download_and_resize (source_bucket , key )
63- s3 .upload_file (resized_path , target_bucket , key )
77+ try :
78+ resized_path = download_and_resize (source_bucket , key , target_bucket )
79+ if resized_path :
80+ print (f"Resized image saved to: { resized_path } " )
81+ else :
82+ print (f"Skipping non-image file: { key } " )
83+ except Exception as e :
84+ print (f"Error processing image: { e } " )
85+ # Continue processing other records even if one fails
0 commit comments