Cloud Computing2025-05-26

Automatically Resize Images in S3 with AWS Lambda - Step-by-Step Tutorial

Automatically Resize Images in S3 with AWS Lambda - Step-by-Step Tutorial
AWSS3LambdaImage Processing

Welcome to this step-by-step tutorial on how to automatically resize images in Amazon S3 using AWS Lambda. As organizations increasingly rely on cloud solutions for storing and managing media, automating image processing tasks such as resizing can save significant time and resources. This guide is designed for developers and cloud architects looking to streamline their image management workflows using AWS services.

Prerequisites

Before we dive into the tutorial, ensure you have the following:

  • An AWS account with access to S3 and Lambda
  • Basic knowledge of AWS services and the AWS Management Console
  • Node.js installed on your local machine for testing purposes

Step 1: Setting Up Your S3 Buckets

In this section, we will create two S3 buckets: one for uploading original images and another for storing the resized versions.

  1. Log into AWS Management Console: Navigate to the S3 service.
  2. Create Buckets:
    • Click "Create bucket" and name it original-images-bucket.
    • Repeat the process to create another bucket named resized-images-bucket.
  3. Set Permissions: Ensure both buckets have the necessary permissions to allow AWS Lambda to read from and write to them.

Step 2: Configuring AWS Lambda

Here, we’ll set up an AWS Lambda function that will automatically resize images when they are uploaded to the original-images-bucket.

  1. Navigate to AWS Lambda: In the AWS Management Console, go to the Lambda service.
  2. Create a New Function:
    • Choose "Author from Scratch."
    • Name your function ResizeImageFunction.
    • Set the runtime to Node.js 14.x.
  3. Set Permissions: Attach the AWSLambdaS3ExecutionRole to your Lambda function to allow access to S3.
  4. Add S3 Trigger:
    • Under the “Configuration” tab, select “Triggers.”
    • Click “Add trigger” and select S3.
    • Choose the original-images-bucket and set the event type to “PUT” to trigger on new uploads.

Step 3: Writing the Lambda Function Code

This section covers writing the code for the Lambda function to resize images.

  1. Install Dependencies: Use the sharp library for image processing. This requires packaging.
    • On your local machine, create a new directory and navigate to it.
    • Run npm init -y to initialize a new Node.js project.
    • Install sharp: npm install sharp.
  2. Write the Lambda Function Code:
    const AWS = require('aws-sdk');
    const S3 = new AWS.S3();
    const Sharp = require('sharp');
    
    exports.handler = async (event) => {
        const Bucket = event.Records[0].s3.bucket.name;
        const Key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
        const sourceBucket = 'original-images-bucket';
        const destinationBucket = 'resized-images-bucket';
    
        try {
            const image = await S3.getObject({ Bucket: sourceBucket, Key }).promise();
            const resizedImage = await Sharp(image.Body).resize(200, 200).toBuffer();
    
            await S3.putObject({
                Bucket: destinationBucket,
                Key,
                Body: resizedImage,
                ContentType: 'image/jpeg'
            }).promise();
    
            console.log(`Successfully resized ${Key} and uploaded to ${destinationBucket}`);
        } catch (error) {
            console.error(`Failed to resize image: ${error}`);
            throw error;
        }
    };
    
  3. Upload the Code: Zip the node_modules directory along with your Lambda function file and upload it to AWS Lambda.

Step 4: Testing the Setup

Finally, we'll test the entire setup to ensure the resizing function works as expected.

  1. Upload an Image: Upload an image to the original-images-bucket using the S3 console or AWS CLI.
  2. Check Resized Image: Navigate to the resized-images-bucket and verify that the resized image has been stored there.

Conclusion

Congratulations! You've successfully set up an automated system to resize images in Amazon S3 using AWS Lambda. This solution can be extended and customized to fit specific needs such as changing image formats or applying different processing techniques.

This tutorial provides a robust foundation for implementing automated image processing workflows in AWS, enabling efficient and scalable media management.

Related Tools


Last updated: May 26, 2025