Resizing image to S3 bucket with lambda trigger with nodejs

I'm new to nodejs and aws, can anyone please point out what is wrong with the following code to resize images in s3 cart.

The program looks like this

 'use strict';
 const AWS = require('aws-sdk');
 const S3 = new AWS.S3({
 accessKeyId: "xxxxxxxxxxxx",
 secretAccessKey: "yyyyyyyyyyy", 
 region: "us-east-1", 
 signatureVersion: 'v4',
 });

const Sharp = require('sharp');
const BUCKET = "patientimg"; 
const URL = "https://s3.ap-south-1.amazonaws.com";
exports.handler = function(event, context, callback) {
const key = event.queryStringParameters.key;
const match = key.match(/(\d+)x(\d+)\/(.*)/);
const width = parseInt(match[1], 10);
const height = parseInt(match[2], 10);
const originalKey = match[3];

S3.getObject({Bucket: BUCKET, Key: originalKey}).promise()
.then(data => Sharp(data.Body)
  .resize(width, height)
  .toFormat('png')
  .toBuffer()
)
.then(buffer => S3.putObject({
    Body: buffer,
    Bucket: BUCKET,
    ContentType: "image/png",
    Key: key,
  }).promise()
)
.then(() => callback(null, {
    statusCode: '301',
    headers: {'location': "${URL}/${key}"},
    body: "",
  })
)
.catch(err => callback(err))
}

      

this is my exact code i am using, output from lambda when tested with "S3 put" request

  {
   "errorMessage": "RequestId: edaddaf7-4c5e-11e7-bed8-13f72aaa5d38 Process exited before completing request"
    }

      

Thank you in advance

+3


source to share


1 answer


Resizing images using lambda is a classic example well explained by the AWS team. Follow their instructions, not something else.

https://aws.amazon.com/blogs/compute/resize-images-on-the-fly-with-amazon-s3-aws-lambda-and-amazon-api-gateway/

Correct resizing code: http://github.com/awslabs/serverless-image-resizing . Everything you found is probably wrong.



It basically works like this:

  • Load this code as a lambda.
  • Go to your lambda triggers tab and copy the url
  • Go to your s3 bucket and set up a redirect rule: to 404, redirect the lambda url. The image will be automatically resized as needed.

All of these steps are detailed on the AWS blog above. The advantage of their approach is that the modified image is not created until it is actually needed, which saves resources.

+1


source







All Articles