Create and use image requests
This solution generates a CloudFront domain name that gives you access to both original and modified images through the image handler API. You can specify parameters such as the image’s location and edits to be made in a JSON object on the frontend.
Follow these step-by-step instructions to create image requests:
Note
The following image formats are supported for modifications: JPG/JPEG, PNG, TIFF/TIF, WEBP, GIF and 8-bit AVIF. For retrieval, the following formats are supported: All those listed previously, as well as AVIF (all bit depths) and SVG. Edited SVG files will be converted to .png by default.
-
Retrieve your API endpoint for the solution. Refer to Use the solution with a frontend application for instructions.
-
In a code sandbox, or in your frontend application, create a new
imageRequestJSON object. This object contains the key-value pairs needed to successfully retrieve and perform edits on your images. Using the following code sample and the sharpdocumentation, adjust the following properties to meet your image editing requirements. -
Bucket - Specify the S3 bucket containing your original image file. This is the name that’s specified in the SourceBuckets template parameter. You can update the image location by adding it into the SOURCE_BUCKETS environment variable of your image handler Lambda function. See Using AWS Lambda environment variables in the AWS Lambda Developer Guide for more information.
-
Key - Specify the filename of your original image. This name should include the file extension and subfolders between its location and the root of the bucket. For example,
folder1/folder2/image.jpeg. -
Edits - Specify image edits as key-value pairs. If you don’t specify image edits, the original image returns with no changes made.
For example, the following code block specifies the image location as
myImageBucketand specifies edits ofgrayscale: trueto change the image to grayscale: -
const imageRequest = JSON.stringify({ bucket: "<myImageBucket>", key: "<myImage.jpeg>", edits: { grayscale: true } })
-
Stringify the JSON request object. For example:
const stringifiedObject = JSON.stringify(<myObject>); -
Base64 encode the JSON string. For example:
const encodedObject = btoa(<stringifiedObject>); -
Append the encoded string onto the CloudFront URL. For example:
const url = '${<ApiEndpoint>}/${<encodedObject>}'; -
Use that URL either in the JavaScript as part of a
GETrequest, or in the frontend as part of an HTMLimgtag’ssrcproperty.
For information regarding how to use additional features in an image request, refer to Dynamically resize photos, Use smart cropping, Use round cropping, and Activate and use content moderation. For additional features supported by sharp, refer to the sharp
Note
The following filters are not supported for multi-page GIF images due to limitations in the underlying libraries: rotate, smartCrop, roundCrop, and contentModeration.