home

Retrieve images from S3 using AWS's serverless image handler

2021-9-21

Using AWS's serverless image handler Cloudformation to easily resize images

I had previously shown how to upload images to an S3 bucket in this post.

Now we need to display those images using a serverless image handler

The normal practice is to serve those files through CloudFront for caching. We also want to be resizing these images to optimize load times.

Conveniently Amazon has a CloudFormation template that takes care of this!

Go here

and press Launch in Console.

s3 Image Handler

Then press next at Create Stack Specify Template.

Enable CORS, add your bucket name to the SourceBuckets, you can deploy a demo UI, I turn this off since I'll be testing it in my app, and leave the rest as is.

Press next until the cloudformation is deployed.

After the cloudformation has formed, and you have it opened, go to outputs and copy the API endpoint, we'll need that in our front end.

const s3res = await Storage.put(file.name, file)
const jsonToUrl = {
  "bucket": process.env.storage.BUCKET,
  "key": `public/${s3res.key}`,
    "edits": {
      "resize": {
        "width": 900,
        "height": 675,
        "fit": "cover"
     }
   }
}
const converting = Buffer.from(JSON.stringify(jsonToUrl)).toString('base64')
const convertedUrl = process.env.img_cloudfront + "/" + converting

In the above code, we define some JSON and encode it to form the URL. (Some sites like Imgix allow you to put the image dimensions directly in the URL)

Notice 'const converting' - In this particular instance, I'm working with Next.js, server-rendered React, on the client-side you can use 'window.btoa(STRING)'. Let's say you want the image without resizing it, just leave out the 'edits' key. Here I resize it to 900x675. Then we add that to our base URL our cloudformation outputted. Then we can use that URL in any '&ltimg src="">'.

Check out the docs, you can do some cool stuff like smart cropping and content moderation.

Now instead of paying for an image processor, we do it ourselves for much cheaper.