Python > Deployment and Distribution > Deployment Platforms > Serverless Computing (e.g., AWS Lambda, Google Cloud Functions, Azure Functions)
AWS Lambda Function for Image Resizing
This code snippet demonstrates a basic AWS Lambda function written in Python that resizes images uploaded to an S3 bucket using the Pillow library. This is a common use case for serverless computing as it allows you to offload image processing tasks without managing dedicated servers.
Prerequisites
Before deploying this Lambda function, you'll need:
Lambda Function Code
This Python code defines the lambda_handler
function, which is the entry point for your Lambda function. It retrieves the image from S3, resizes it to a thumbnail, and saves the thumbnail back to S3 in a 'thumbnails' folder.
import boto3
from io import BytesIO
from PIL import Image
import os
s3 = boto3.client('s3')
def lambda_handler(event, context):
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
size = 128 # Desired thumbnail size
try:
response = s3.get_object(Bucket=bucket, Key=key)
image_data = response['Body'].read()
image = Image.open(BytesIO(image_data))
image.thumbnail((size, size))
buffer = BytesIO()
image.save(buffer, 'JPEG') # Save as JPEG
buffer.seek(0)
new_key = 'thumbnails/' + key # Save thumbnail to thumbnails folder
s3.put_object(Bucket=bucket, Key=new_key, Body=buffer, ContentType='image/jpeg')
return {
'statusCode': 200,
'body': f'Thumbnail created successfully for {key} and saved to {new_key}'
}
except Exception as e:
print(e)
print(f'Error processing image {key} from bucket {bucket}.')
raise e
Explanation
event
parameter contains information about the event that triggered the Lambda function (in this case, an S3 object creation).context
parameter provides runtime information about the Lambda function.image.thumbnail()
, and saves the thumbnail back to S3.
Deployment
To deploy this Lambda function:
Real-Life Use Case
This pattern is commonly used in web applications where users upload images. Generating thumbnails serverlessly allows for faster page loading times and reduces the load on the main application server.
Best Practices
When to use them
Use Serverless Computing when:
Memory Footprint
The memory footprint of this Lambda function depends on the size of the images being processed and the libraries being used (Pillow). Optimize image processing techniques to minimize memory usage. Consider increasing Lambda's memory allocation if you are processing large images.
Alternatives
Alternatives to Lambda for image processing include:
Pros
Cons
FAQ
-
How do I handle errors in my Lambda function?
You can use try-except blocks to catch exceptions and log errors using CloudWatch Logs. You can also use dead-letter queues (DLQs) to handle failed events. -
How do I manage dependencies for my Lambda function?
You can package your dependencies along with your code in a zip file or use Lambda Layers to share dependencies across multiple functions. -
How do I monitor my Lambda function?
You can use CloudWatch Metrics and Logs to monitor the performance and health of your Lambda function. AWS X-Ray can be used for tracing requests through your serverless application.