-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
78 lines (63 loc) · 2.73 KB
/
lambda_function.py
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import os
import boto3
from PIL import Image
import tempfile
import traceback
s3_client = boto3.client('s3')
MAX_DIMENSIONS = (400, 400)
def resize_image(image_path, resized_path, original_format):
with Image.open(image_path) as image:
# Calculate the thumbnail size
width, height = image.size
max_width, max_height = MAX_DIMENSIONS
if width > max_width or height > max_height:
ratio = max(width / max_width, height / max_height)
width = int(width / ratio)
height = int(height / ratio)
size = (width, height)
# Generate the resized image
image.thumbnail(size)
# Convert image to RGB if necessary
if image.mode in ("RGBA", "P"):
image = image.convert("RGB")
# Save the resized image
image.save(resized_path, format=original_format)
def lambda_handler(event, context):
try:
# Debugging: Print the event
print("Received event:", event)
# Get bucket and object key from the event
source_bucket = event['Records'][0]['s3']['bucket']['name']
source_key = event['Records'][0]['s3']['object']['key']
destination_bucket = 'resized-images'
print(f"Source bucket: {source_bucket}, Source key: {source_key}")
with tempfile.TemporaryDirectory() as tmpdir:
download_path = os.path.join(tmpdir, source_key)
# Extract the filename and extension
base_filename, ext = os.path.splitext(source_key)
resized_filename = f"{base_filename}{ext}"
upload_path = os.path.join(tmpdir, resized_filename)
# Download the image from S3
print("Downloading image...")
s3_client.download_file(source_bucket, source_key, download_path)
print("Image downloaded to", download_path)
# Determine the image format
with Image.open(download_path) as image:
original_format = image.format
print("Original image format:", original_format)
# Resize the image
print("Resizing image...")
resize_image(download_path, upload_path, original_format)
print("Image resized and saved to", upload_path)
# Upload the resized image to the destination bucket
print("Uploading resized image...")
s3_client.upload_file(upload_path, destination_bucket, resized_filename)
print("Resized image uploaded to", destination_bucket)
return {
'statusCode': 200,
'body': f"Image {source_key} resized and uploaded to {destination_bucket}"
}
except Exception as e:
print("Error occurred:", e)
traceback.print_exc()
raise e