I'm trying to write a lambda that puts a watermark on an image, then saves the result to S3. I'm using the Sharp library to do so. I'm deploying with Serverless Framework.
I'm unsure how to 'include' the image with the lambda. I'll be watermarking millions of images, so I want to avoid having to 'read' the image from S3 every time and I'd like to just have it be included in the lambda package.
let overlayResp;
try {
const overlayImg = await Sharp(sourceImage.Body)
.composite([{input: './logos/white.png', gravity: 'southeast' }])
.toFormat('jpeg').toBuffer();
overlayResp = await s3.putObject({
Bucket: IMAGE_BUCKET,
Body: overlayImg,
Key: `${filename.replace('original', 'overlay')}`
}).promise();
} catch (err) {
console.error('Overlay err :>> ', err); //TODO: DLQ
}
I've tried including the image in the 'logos' folder alongside my processNewImage.js folder like so:
Using the above code. It errors out saying 'Input file is missing'.
I've tried an to import the image const WHITE = require('/logos/white.png');
and changing the composite line to .composite([{input: WHITE, gravity: 'southeast' }])
and the result is that the code doesn't even run (Cannot find module '/logos/white.png
).
It feels like the lambda package doesn't have the image included. How can I include it and/or make a reference to it?
The path you are using (/logos/white.png
) is an absolute path and that means that your code is "looking" in the wrong place.
I am not 100% sure but one of the following two options should solve your issue:
./logos/white.png
)LAMBDA_TASK_ROOT
environment variable:let path = `${process.env.LAMBDA_TASK_ROOT}/logos/white.png`
Documentation: https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime
Another option is split the application code and the assets like the image up. The image would go into a Lambda layer which you would be able find in another directory on the Lambdas disk:
https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html#configuration-layers-path