How can I set up S3 Bucket notification for triggering an AWS lambda function?

38    Asked by DavidWHITE in AWS , Asked on Apr 12, 2024

 I am currently working on a particular task in which I need to process images uploaded for an AWS S3 bucket in real-time. How can I set up S3 bucket notification for triggering an AWS lambda function whenever a new image is uploaded, and then have the lambda function process the image data? 

Answered by David

In the context of AWS, here is how you can set up S3 Bucket notification for triggering an AWS lambda function by using the coding:-

Create an S3 Bucket

If you do not have the S3 Bucket already, then you can create one by using the AWS management console or you can use the AWS CLI:-

Aws s3api create-bucket –bucket your-bucket-name –region your-region –create-bucket-configuration LocationConstraint=your-region

Create an AWS lambda function

Here is an example given in Python programming language of how you can process images uploaded to the S3 Bucket. This function would resize the image by using the pillow library and would save the resized image back to the S3 bucket:-

Import json
Import boto3
From PIL import Image
From io import BytesIO
S3_client = boto3.client(‘s3’)
Def lambda_handler(event, context):
    # Get the bucket name and object key from the S3 event
    Bucket_name = event[‘Records’][0][‘s3’][‘bucket’][‘name’]
    Object_key = event[‘Records’][0][‘s3’][‘object’][‘key’]
    # Download the image from S3
    Response = s3_client.get_object(Bucket=bucket_name, Key=object_key)
    Image_data = response[‘Body’].read()
    # Process the image (resize, for example)
    Img = Image.open(BytesIO(image_data))
    Resized_img = img.resize((200, 200)) # Resize the image to 200x200 pixels
    # Save the resized image to S3
    Resized_image_data = BytesIO()
    Resized_img.save(resized_image_data, format=’JPEG’)
    Resized_image_data.seek(0)
    # Upload the resized image back to S3
    S3_client.put_object(Bucket=bucket_name, Key=f”resized/{object_key}”, Body=resized_image_data)
    Return {
        ‘statusCode’: 200,
        ‘body’: json.dumps(‘Image processed and resized successfully!’)
    }

If you are keen to use the java programming language for creating the AWS lambda function then here is the example given below:-

Package com.example;
Import com.amazonaws.services.lambda.runtime.Context;
Import com.amazonaws.services.lambda.runtime.RequestHandler;
Import com.amazonaws.services.lambda.runtime.events.S3Event;
Import software.amazon.awssdk.core.SdkBytes;
Import software.amazon.awssdk.regions.Region;
Import software.amazon.awssdk.services.s3.S3Client;
Import software.amazon.awssdk.services.s3.model.GetObjectRequest;
Import software.amazon.awssdk.services.s3.model.PutObjectRequest;
Import software.amazon.awssdk.services.s3.model.S3Exception;
Import software.amazon.awssdk.services.s3.model.S3Object;
Import javax.imageio.ImageIO;
Import java.awt.*;
Import java.awt.image.BufferedImage;
Import java.io.ByteArrayInputStream;
Import java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import java.io.InputStream;
Public class ImageProcessingLambda implements RequestHandler {
    Private static final String RESIZED_FOLDER = “resized/”;
    Private final S3Client s3Client = S3Client.builder()
            .region(Region.US_EAST_1)
            .build();
    @Override
    Public String handleRequest(S3Event s3Event, Context context) {
        Try {
            For (S3Event.S3EventRecord record : s3Event.getRecords()) {
                String bucketName = record.getS3().getBucket().getName();
                String objectKey = record.getS3().getObject().getKey();
                // Download the image from S3
                S3Object s3Object = s3Client.getObject(GetObjectRequest.builder()
                        .bucket(bucketName)
                        .key(objectKey)
                        .build());
                InputStream imageInputStream = s3Object.read();
                // Process the image (resize, for example)
                BufferedImage originalImage = ImageIO.read(imageInputStream);
                BufferedImage resizedImage = resizeImage(originalImage, 200, 200);
                // Upload the resized image back to S3
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(resizedImage, “jpg”, outputStream);
                Byte[] resizedImageBytes = outputStream.toByteArray();
                S3Client.putObject(PutObjectRequest.builder()
                        .bucket(bucketName)
                        .key(RESIZED_FOLDER + objectKey)
                        .contentType(“image/jpeg”)
                        .contentLength((long) resizedImageBytes.length)
                        .build(), SdkBytes.fromByteArray(resizedImageBytes));
                Context.getLogger().log(“Resized image uploaded to S3.”);
            }
        } catch (IOException | S3Exception e) {
            Context.getLogger().log(“Error: “ + e.getMessage());
            Return “Error processing image: “ + e.getMessage();
        }
        Return “Image processing complete.”;
    }
    Private BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
        Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT);
        BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = resizedImage.createGraphics();
        Graphics2D.drawImage(resultingImage, 0, 0, null);
        Graphics2D.dispose();
        Return resizedImage;
    }
}


Your Answer

Interviews

Parent Categories