When developing an application it is important to have assets resized for different capabilities, screen sizes, and resolutions. This is important for many reasons.
  1. Low resolution images on high resolution displays make a bad UX
  2. High resolution images on low resolution displays waste both bandwidth and device and server resources
  3. Creating several thumbnails during image upload, can be a lot of workand limits the agility for future redesigns.
  4. Adopting an image in-app and cropping/resizing it may be heavy for the app especially if you use Frameworks.

Resizing on the fly

Instead of processing and resizing images into all necessary sizes upon upload, the approach of processing images on the fly has several upsides:
  1. Increased agility
  2. Reduced storage costs
  3. Resilience to failure
In this post, we’ll be using a different approach and outline a method of lazily generating images, in which a resized asset is only created if a user requests that specific size.

Creating a new bucket

Open s3 console

Creating CloudFront distribution for SSL

Open CloudFront console
This can take few mins, wait until the status changes from ‘in progress’ to ‘deployed’. After the status is changed to deployed, note the CloudFront domain name. It should look similar to blabla.cloudfront.net

Setting up permission for Lambda function

Open IAM console
Creating policy:
Creating role:

Creating Lambda function

Open Lambda console

Setting up S3 redirection rule

Ok we’re almost there, phew that was a lot of configurations.
<RoutingRules>
  <RoutingRule>
    <Condition>
      <KeyPrefixEquals/>
      <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
    </Condition>
    <Redirect>
      <Protocol>https</Protocol>
      <HostName>__YOUR_API_HOSTNAME_HERE</HostName>
      <ReplaceKeyPrefixWith>default/imageResize?key=</ReplaceKeyPrefixWith>
      <HttpRedirectCode>307</HttpRedirectCode>
    </Redirect>
  </RoutingRule>
</RoutingRules>

Test image resizing

Upload a test image into your bucket to for testing. Once uploaded, try to retrieve resized versions of the image using your CloudFront domain:
You should see a smaller version of the test photo. If not, choose Monitoring in your Lambda function and check CloudWatch Logs for troubleshooting. You can also refer to the serverless-image-resizing GitHub repo for a working example that you can deploy to your account.

YOU MADE IT!!! 🚀🎉🎊