Node.js Tutorial to Resize Images on Upload Using Amazon AWS Lambda in S3 Bucket Full Project For Beginners

 

 

index.js

 

 

// dependencies
const AWS = require('aws-sdk');
const util = require('util');
const Sharp = require('sharp');

// get reference to S3 client
const s3 = new AWS.S3();

exports.handler = async (event, context, callback) => {

    // Read options from the event parameter.
    console.log("Reading options from event:\n", util.inspect(event, { depth: 5 }));
    const srcBucket = event.Records[0].s3.bucket.name;
    const srcKey = `${event.Records[0].s3.object.key}`;
    const thumbs = ['50x50', '400x400']
    const mimetypeImage = [
        'image/jpeg',
        'image/png',
        'image/bmp',
        'image/heic',
        'image/heif',
        'image/pipeg',
        'image/x-icon',
    ];


    for (const thumb of thumbs) {
        console.log(`srcKey.startsWith(${thumb}): `, srcKey.startsWith(thumb))
        if (srcKey.startsWith(thumb)) return
    }

    // Download the image from the S3 source bucket.

    try {
        const params = {
            Bucket: srcBucket,
            Key: srcKey
        };
        var origimage = await s3.getObject(params).promise();

    } catch (error) {
        console.log(error, 'getObject');
        return;
    }

    // set thumbnail width. Resize will set the height automatically to maintain aspect ratio
    const bufferDataConvert = origimage.Body;
    const contentType = origimage.ContentType

    if (!mimetypeImage.includes(contentType)) return
    const images = []
    for (let thumb of thumbs) {
        const [w, h] = thumb.split('x');
        let bufferData = bufferDataConvert;
        if (w && h) {
            bufferData = await Sharp(bufferDataConvert)
                .resize(Number(w), Number(h), {
                    withoutEnlargement: true,
                    fit: 'inside',
                })
                .toBuffer();

            images.push({
                key: `${thumb}/${srcKey}`,
                bufferData,
            });
        }
    }


    // Upload the thumbnail image to the destination bucket
    try {
        if (!images.length) return
        const putObjects = images.map((item) => {
            return s3
                .putObject({
                    ACL: 'public-read',
                    Body: item.bufferData,
                    Bucket: srcBucket,
                    ContentType: contentType,
                    Key: item.key,
                })
                .promise();
        });

        await Promise.all(putObjects);
    } catch (error) {
        console.log(error, 'putObject');
        return;
    }

    console.log('Successfully resized ' + srcBucket + '/' + srcKey);
};

Leave a Reply