This repository deploys an AWS Lambda Function that resizes images using ImageMagick.
Blog post: https://www.bytescale.com/blog/aws-lambda-image-resize/
Important:
- Replace
my-lambda-function-code
andmy-images
with unique S3 bucket names!
-
Checkout the repository:
git clone git@github.com:bytescale/aws-lambda-image-magick-resize-example.git cd aws-lambda-image-magick-resize-example
-
Install NPM dependencies:
npm install
-
Create the S3 bucket stack (remember: change the bucket names in
ParameterValue
below):aws cloudformation create-stack \ --stack-name my-bucket-stack \ --parameters ParameterKey=LambdaCodeBucketName,ParameterValue=my-lambda-function-code \ ParameterKey=ImageBucketName,ParameterValue=my-images \ --template-body file://buckets-cloudformation.yml
-
Update
function.js
>imageBucketName
to your image bucket's name. -
Upload the Lambda Function's code:
zip -ry function-dist.zip . aws s3 cp function-dist.zip s3://my-lambda-function-code/AwsLambdaImageResizeExample.zip
-
Deploy the Lambda Function (remember: change the bucket names in
ParameterValue
below):aws cloudformation create-stack \ --stack-name my-image-resize-lambda \ --parameters ParameterKey=LambdaCodeBucketName,ParameterValue=my-lambda-function-code \ ParameterKey=ImageBucketName,ParameterValue=my-images \ --template-body file://function-cloudformation.yml \ --capabilities CAPABILITY_NAMED_IAM
-
Wait for the Lambda Function's stack to complete:
aws cloudformation describe-stack-events \ --stack-name my-image-resize-lambda
Note: the latest event should read
"ResourceStatus": "CREATE_COMPLETE"
.
-
Upload the image to resize:
aws s3 cp test-image.jpg s3://my-images/original-image.jpg
-
Invoke the function:
aws lambda invoke \ --function-name AwsLambdaImageResizeExample \ function-result.json
-
"See" the result:
cat function-result.json
Outputs:
{ "isBase64Encoded": true, "statusCode": 200, "headers": { "content-type": "image/jpg" }, "body": "/9j/4AAQSkZJRg...9k=" }
Note: AWS Lambda only supports JSON responses.
body
contains the resized image as a base64-encoded string: to return the raw image, you'll need to put API Gateway in front of the Lambda function.