This example code shows how to easily use Sharp to resize images in a Lambda.
This example code shows image resizing, either based on binary input to an API Gateway and Lambda, or as an event-driven flow from images placed in an S3 subpath.
For the API Gateway case, it:
For the S3 event-driven case it does the same, but assumes that the input is a JPG file added to the original
path of an S3 bucket.
All in all, the infrastructure used is API Gateway v2 (HTTP API), Lambda, and S3.
This example simplifies what has been a complicated and tricky process using Lambda Layers and other workarounds - doing it this way is much easier and more straightforward.
It is assumed that:
Make sure to set a unique value in serverless.yml
for custom.imagesBucketName
.
If you want to set the paths for where to locate the original files and the output destination, they are available under custom.imagesBucketPrefix
(Default: original/
) and custom.resizedImagesPath
(Default: images-resized
).
Also, you can change the resizing settings in src/handler.ts
in the conversions
object.
Run npm start
.
Run npm run deploy
.
Run npm run teardown
.
Using the provided example image, you could call your API similar to this:
curl -X POST https://RANDOM.execute-api.REGION.amazonaws.com/ \
-H "Content-Type: image/jpg" \
--data-binary '@image.jpg'