This is a simple example of how to use AWS Lambda to resize images on the fly using Amazon CloudFront.
- Low-resolution images on high-resolution displays create a bad user experience.
- High-resolution images on low-resolution displays waste bandwidth, device, and server resources, especially when using a framework that adopts images in-app and crops or resizes images, making the app heavy.
Add query parameters. That's it.
- width
- height
- format ('auto' option checks the Accept request header)
- quality (0~100, default: 100)
- https://your-domain/images/hangang-river.jpeg?width=1100 (940KB)
- https://your-domain/images/hangang-river.jpeg?width=1100&format=webp (658KB)

- The user requests an image from CloudFront.
- CloudFront forwards the request to the Lambda function.
- The Lambda function resizes the image and returns it to CloudFront.
- CloudFront caches the image and returns it to the user.
- The next time the same image is requested, CloudFront returns the cached image.
- If the image is updated, the cache is invalidated and the process starts over.
- The Lambda function is only invoked when the image is requested for the first time or when the cache is invalidated.
- Build the Docker image:
docker build -t lambda-image-resizer .
- Create a directory to store test images and run the Docker container:
mkdir -p test-images
docker run -it -v $(pwd)/test-images:/app/test-images lambda-image-resizer /bin/sh
- After accessing the container, you can run the test as follows:
aws-lambda-local -l index.mjs -h handler -e test-event.json
- Modify the following environment variables in the Dockerfile if needed:
- AWS_REGION: AWS region
- S3_BUCKET: S3 bucket name
- If AWS credentials are required, uncomment the relevant section and provide the values.
- To test with actual images, place test image files in the
test-images
directory and update the URI path intest-event.json
to match the image file path.
This test environment allows you to test the Lambda function's image processing logic locally without connecting to actual AWS resources. To connect to a real S3 bucket, set up appropriate AWS credentials.
Create a Lambda function (choose us-east-1 to use the CloudFront response trigger)

Create a Cloud9 environment for writing the Lambda function source code

Write the Lambda function
Write the code (See this repository's source code)

Upload the Lambda function

Select "Directory" -> "No" -> Select the project folder -> Open (after a few minutes, a completion message will appear)
Add a Trigger

Deploy
