Serverless File Processing: Resize Images Automatically Using Lambda + S3
Learn how to automatically resize images using AWS Lambda and S3, creating a fully serverless file processing workflow.
Serverless File Processing: Resize Images Automatically Using Lambda + S3
Handling images at scale can be challenging. Whether it's for a website, app, or storage optimization, resizing images automatically saves time and reduces storage costs.
With AWS Lambda and S3, you can build a fully serverless workflow that resizes images automatically whenever a new file is uploaded.
How It Works
The workflow is simple:
This approach requires no servers, scales automatically, and integrates seamlessly with your AWS environment.
AWS Services Used
Lambda Function Code (Node.js)
import { S3Client, GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3"
import sharp from "sharp"
const s3 = new S3Client({ region: "us-east-1" })
export const handler = async (event) => {
for (const record of event.Records) {
const bucket = record.s3.bucket.name
const key = record.s3.object.key
// Get the original image
const original = await s3.send(
new GetObjectCommand({ Bucket: bucket, Key: key })
)
const buffer = await streamToBuffer(original.Body)
// Resize the image
const resized = await sharp(buffer)
.resize({ width: 300 }) // Resize width to 300px
.toBuffer()
// Save resized image to another folder
await s3.send(
new PutObjectCommand({
Bucket: bucket,
Key: 'resized/${key}',
Body: resized,
ContentType: "image/jpeg"
})
)
console.log('Resized image saved: resized/${key}')
}
}
// Helper function to convert stream to buffer
const streamToBuffer = async (stream) => {
const chunks = []
for await (const chunk of stream) {
chunks.push(chunk)
}
return Buffer.concat(chunks)
}Setting Up S3 Event Trigger
Now, whenever you upload an image to 'uploads/', Lambda will automatically resize it and save it in 'resized/'.
Benefits of This Serverless Approach
Extending This Workflow
Final Thoughts
Serverless file processing with Lambda + S3 is a powerful pattern for modern applications. It reduces operational overhead, is cost-efficient, and can be extended to handle videos, PDFs, or any other files.
Start small with image resizing and expand your serverless workflows as your application grows. 🚀