简体   繁体   中英

Resizing the image in S3 bucket from lambda trigger using nodejs

I newbie to nodejs and aws, Can anyone point out whats wrong with the following code to resize the images in s3 bucket

Program as follows

 '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'm using, output from lambda when testing with "S3 put" request

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

Thanks in advance

Resizing images using a lambda is a classic example that has been 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/

The correct resizing code is: http://github.com/awslabs/serverless-image-resizing . Whatever you found is probably wrong.

Basically it works like this:

  • Upload this code as your lambda.
  • Go to the triggers tab of your lambda and copy the URL
  • Go to your s3 bucket and set up a redirection rule: on 404, redirect to the lambda URL. The image will be automatically resized when requested.

All of these steps are well documented in detail at the AWS blog above. The benefit of their approach is that the resized image is not created until it is actually needed, which saves on resources.

You can use thisAWS Lambda image resizer .

It's built with Node.js and with options to build your own settings. You just need to follow the steps here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM