How to Create Thumbs with AWS Lambda

Oleksii Kosynskyi
AWS in Plain English
3 min readMar 8, 2022

--

A fairly common task for a web developer is to cut pictures. I bring to your attention a ready-made solution using Serverless Framework, AWS Lambda, S3, FFmpeg.

The architecture of this solution

The Lambda function listens to the file upload event in Source S3 Bucket and fires the Lambda Function. From the input parameters of the function, we can extract the S3 name and file key.

The heigh-level algorithm

  1. Get source file key from input parameters
  2. Download the image file from Source S3 Bucket
  3. Crop and resize image file to thumbs
  4. Upload results to Destination S3 Bucket. It is very important to upload to another bucket because if you upload a file to the same bucket, the Lambda will be triggered again and it will cut the already cut pictures (recursion, for which you will have to pay)

Let’s move on to practice

For crop and resize images, we will use FFmpeg. Here is an example of how to make an image smaller and cropped to 300x300px:

ffmpeg -i source.jpg -filter:v "scale=300:-1,crop=300:300:0:0" -y crop300x300.jpg

Resize and crop source.jpg to crop300x300.jpg

Everything works great locally, but there is no FFmpeg in the Lambda. Therefore, we need a binary file in Lambda, which we put inside the lambda layer.

To run console command from JavaScript, use child_process:

Also, we need to take meta information from the image: width, height, angle of rotation (required for the correct rotation of the image if you take a picture on your phone). We can get this information by using FFprobe. So, let’s make a function that will get this data:

Now we can create the main functionality — the function of the image resize and crop:

The main code of Lambda will look like this:

The config.RESOLUTIONS is a configuration constant that can be used to specify which formats images need to be converted to. For example, I made several options:

To deploy Lambda to AWS let’s use Serverless Framework. Here is a sample config:

Now we can run sls deploy and Serverless Framework will deploy all things to your AWS account.

Lambda Function after deployment finished

Let’s upload source.jpg to Source S3 Bucket and check how our converter works:

Conclusion

Lambda function has a free tier of usage (1M calls and 400,000 GB-seconds of execution per month), so you can use this code in your project and get a free image converter.
Also, you can read Cases for AWS Lambda usage to understand more deeply how you can use the Lambda function.

The whole code is here. So, you can pull and check it. If you have any suggestions, please comment or create a PR. Thanks for reading.

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.

--

--