Auto-Compressing Uploaded Images on AWS S3 with Lambda (Zero Server Management)
Instead of resizing images inside your main backend API—which blocks threads and eats up memory—you can offload the whole process to an event-driven workflow using Amazon S3 and AWS Lambda
**Auto-Compressing Uploaded Images on AWS S3 with Lambda (Zero Server Management)**If you have ever built an application where users upload profile pictures or media, you know the pain of uncompressed files. One user uploads a 12MB raw photo from their phone, and suddenly your frontend load times tank and your bandwidth costs creep up.Instead of resizing images inside your main backend API—which blocks threads and eats up memory—you can offload the whole process to an event-driven workflow using Amazon S3 and AWS Lambda.Here is how I set up an automated image optimization pipeline in under 15 minutes.
The Architecture
The flow is completely serverless and runs only when needed:
- A user uploads a raw image to an S3 Source Bucket.
- S3 triggers an Event Notification upon object creation.
- AWS Lambda wakes up, grabs the image, compresses it using Python (
Pillow), and saves the lightweight version to a Destination Bucket.
(Tip: Always use two separate buckets—one for raw uploads and one for processed images. Writing back to the same bucket on an
ObjectCreated event will trigger an infinite Lambda loop and rack up a surprise bill!)
Step 1: Create Your Two S3 BucketsHead over to the S3 console and create two buckets in the same AWS Region:
-
my-app-raw-uploads
-
my-app-optimized-images
Keep the default Block all public access settings enabled for now.
Step 2: Set Up the IAM Execution RoleYour Lambda function needs permission to read from the first bucket, write to the second bucket, and log its output to CloudWatch.Create a new IAM Role for Lambda and attach a custom inline policy like this:json
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::my-app-raw-uploads/*" }, { "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::my-app-optimized-images/*" } ]}Use code with caution.(Don't forget to also attach the standard
AWSLambdaBasicExecutionRole managed policy so you can view logs in CloudWatch.)
Step 3: Write the Lambda FunctionCreate a new Lambda function using the Python 3.12 runtime and assign the IAM role you just created.Because the Python image library
Pillow isn't included in the default Lambda runtime, you will need to attach a Lambda Layer containing Pillow (you can easily grab a pre-built ARN from Klayers on GitHub or package it via Docker).Once your layer is attached, drop this code into lambda_function.py :pythonimport osimport boto3from PIL import Imageimport io
s3 = boto3.client('s3')DEST_BUCKET = os.environ.get('DEST_BUCKET', 'my-app-optimized-images')
def lambda_handler(event, context): # Get bucket and file key from the S3 event source_bucket = event['Records'][0]['s3']['bucket']['name'] key = event['Records'][0]['s3']['object']['key'] # Download the image into memory response = s3.get_object(Bucket=source_bucket, Key=key) image_content = response['Body'].read() # Open and compress the image with Image.open(io.BytesIO(image_content)) as img: # Convert RGBA to RGB if saving as JPEG if img.mode in ("RGBA", "P"): img = img.convert("RGB") output_buffer = io.BytesIO() img.save(output_buffer, format='JPEG', optimize=True, quality=75) output_buffer.seek(0) # Upload the optimized image to the destination bucket s3.put_object( Bucket=DEST_BUCKET, Key=f"compressed-{key}", Body=output_buffer, ContentType='image/jpeg' ) return { 'statusCode': 200, 'body': f'Successfully compressed {key}' }Use code with caution.
Step 4: Connect the S3 Trigger
- Open your Lambda function overview and click Add trigger.
- Select S3 from the dropdown.
- Choose your
my-app-raw-uploadsbucket.
- Set the Event type to All object create events.
- Acknowledge the recursive invocation warning (since we are using two separate buckets, we are safe!) and click Add.
Testing It OutUpload a large
.jpg or .png file into your raw bucket. Within a couple of seconds, check your destination bucket—you should see a compressed- version of your image sitting there at roughly 20–30% of the original file size with almost no visible drop in quality.**Over to You!**How are you handling media optimization in your serverless apps? Do you stick with Lambda, or have you moved over to CloudFront Functions or third-party CDNs? Drop your setup in the comments! #aws #serverless #lambda #s3 #python #aws-community-builders Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article