DEV Community

CodeSolutionsHub
CodeSolutionsHub

Posted on

Automate Image Resizing in AWS S3 with Serverless Computing

Introduction:

In today’s digital age, images play a crucial role in web applications. However, managing and serving images efficiently can be a challenge. That’s where serverless computing comes to the rescue. In this comprehensive guide, we’ll walk you through the process of setting up a serverless image resizing solution using AWS Lambda and S3.

Project: Serverless Image Resizer

Overview:

The goal of this project is to create a Lambda function that automatically resizes images uploaded to an S3 bucket. This solution will save you time, resources, and the hassle of manually resizing images for different use cases, making it a valuable addition to your toolkit.

Skills Gained:

By completing this project, you’ll acquire essential skills in event-driven Lambda functions, S3 triggers, and image processing with Lambda. You’ll also gain hands-on experience in implementing a practical serverless solution that can be adapted to various scenarios.

Step-by-Step Implementation:

Step 1: Set Up Your AWS Environment

Before we dive into the project, ensure you have an AWS account and the necessary permissions to create Lambda functions and S3 buckets.

Step 2: Create an S3 Bucket

  1. Log in to your AWS Management Console.
  2. Navigate to the S3 service.
  3. Click “Create bucket” and follow the prompts to configure your bucket. Make sure to choose a unique name.

Step 3: Create an AWS Lambda Function

  1. In the AWS Management Console, go to AWS Lambda.
  2. Click “Create function.”
  3. Choose “Author from scratch.”
  4. Provide a name for your function, select the preferred runtime (e.g., Python), and set up a new execution role with basic Lambda permissions.
  5. Click “Create function.”

Step 4: Add S3 permission to your Lambda role

  1. Select Configuration Tab.
  2. Go to Permissions
  3. Click on the Role name and assign AmazonS3FullAccess

Step 5: Configure S3 Trigger for the Lambda Function

  1. In your Lambda function’s configuration, click on “Add trigger.”
  2. Select “S3” as the trigger source.
  3. Configure the trigger to activate on object creation in your S3 bucket.

Image description

Step 6: Write the Lambda Function

Now comes the heart of our project: writing the Lambda function. Below is a Python example that resizes images using the pillow library and stores them back in the S3 bucket:

import os
from io import BytesIO
from PIL import Image
import boto3

s3 = boto3.client('s3')

def lambda_handler(event, context):
    # Get the uploaded image details from the S3 event
    record = event['Records'][0]
    bucket = record['s3']['bucket']['name']
    destination_bucket = '<destination_bucket_name>' # replace your destination bucket name here
    key = record['s3']['object']['key']

    # Download the image from S3
    response = s3.get_object(Bucket=bucket, Key=key)
    image_data = response['Body'].read()

    # Resize the image
    img = Image.open(BytesIO(image_data))
    img.thumbnail((200, 200))  # Resize to 200x200 pixels

    # Save the resized image to S3
    resized_key = os.path.splitext(key)[0] + '-resized.jpg'
    with BytesIO() as output:
        img.save(output, format="JPEG")
        output_data = output.getvalue()
        s3.put_object(Bucket=destination_bucket, Key=resized_key, Body=output_data)

    return {
        'statusCode': 200,
        'body': 'Image resized successfully.'
    }
Enter fullscreen mode Exit fullscreen mode

Important thing to note here, always use separate bucket (destination_bucket) for storing resized image otherwise you may end up in infinite loop and your cost might be infinite too. In practice, people have lost thousands of dollars by doing such small mistakes.

Step 7: Add lambda layer for pillow library

At the end of lambda function, you will find add layer functionality. Specify an ARN.

arn:aws:lambda:us-east-1:770693421928:layer:Klayers-p39-pillow:1

Reference: https://github.com/keithrozario/Klayers/#option-1-using-the-console

Image description

Step 8: Deploy and Test Your Serverless Image Resizer

  1. Save your Lambda function code and deploy it.
  2. Upload an image to your S3 bucket. Your Lambda function should automatically resize the image and store it in a “destination_bucket”.
  3. Test different image sizes and ensure that the Lambda function consistently resizes them as expected.

Conclusion:

Congratulations! You’ve successfully created a serverless image resizer using AWS Lambda and S3. This project not only demonstrates the power of serverless computing but also equips you with valuable skills in event-driven architecture and image processing. Feel free to adapt and expand this solution for various image-related tasks in your applications. Happy coding!

Checkout more here

Top comments (0)