AWS Lambda调整大小时未定义sharp的错误

时间:2017-08-05 19:48:18

标签: aws-lambda sharp

以下代码可以正常工作,直到我尝试添加overlayWith。叠加图像是png并且小于调整大小的图像。我使用的Lambda函数包来自https://aws.amazon.com/blogs/compute/resize-images-on-the-fly-with-amazon-s3-aws-lambda-and-amazon-api-gateway/

'use strict';

const AWS = require('aws-sdk');
const S3 = new AWS.S3({
  signatureVersion: 'v4',
});
const Sharp = require('sharp');

const BUCKET = process.env.BUCKET;
const URL = process.env.URL;


exports.handler = function(event, context, callback) {
  const key = event.queryStringParameters.key;
  var match = key.match(/(\_[xsm][smd]).(jpg)/);
  var version = (match[1]);
 console.log("Match 1: " + (match[1]));
 console.log("Match 2: " + (match[2]));

  var width = 400;
  // IF version = "_md" then 1000 elseif _xs then 100 else 400
  if (version == "_md") {
      width = 1000;
  } else if (version=="_xs") {
      width = 100;
  }

  console.log("key: " + event.queryStringParameters.key);


   var originalKey = key.replace(/\_[xsm][smd]/g, "");
   var newKey = "resized/" + key;
   console.log("OriginalKey: " + originalKey)
   console.log("Bucket: " + URL)
   console.log("NewKey: " + newKey)

  S3.getObject({Bucket: BUCKET, Key: originalKey}).promise()
    .then(data => Sharp(data.Body)
      // .resize(width, height)
      .resize(width, width)
      .max()
      .overlayWith('s3-us-west-2.amazonaws.com/s.cdpn.io/someimage.png', { gravity: sharp.gravity.northeast } )
      .toFormat('jpeg')
      .toBuffer()
    )
    .then(buffer => S3.putObject({
        Body: buffer,
        Bucket: BUCKET,
        ContentType: 'image/jpeg',
        Key: newKey, // newKey
      }).promise()
    )
    .then(() => callback(null, {
        statusCode: '302',
        headers: {'location': `${URL}/${newKey}`}, 
        body: '',
      })
    )
    .catch(err => callback(err))
}

这是日志错误

{
    "errorMessage": "sharp is not defined",
    "errorType": "ReferenceError",
    "stackTrace": [
        "S3.getObject.promise.then.data (/var/task/index.js:42:92)",
        "process._tickDomainCallback (internal/process/next_tick.js:135:7)"
    ]
}

来自http://sharp.dimens.io/en/stable/api-composite/

的示例代码
sharp('input.png')
  .rotate(180)
  .resize(300)
  .flatten()
  .background('#ff6600')
  .overlayWith('overlay.png', { gravity: sharp.gravity.southeast } )
  .sharpen()
  .withMetadata()
  .quality(90)
  .webp()
  .toBuffer()
  .then(function(outputBuffer) {
    // outputBuffer contains upside down, 300px wide, alpha channel flattened
    // onto orange background, composited with overlay.png with SE gravity,
    // sharpened, with metadata, 90% quality WebP image data. Phew!
  });

1 个答案:

答案 0 :(得分:2)

当你require锐利时,你将它保存在一个带有大写'S'的变量Sharp中。您可以在代码中以这种方式使用它,但sharp.gravity.northeast除外。这就是它产生错误的原因 - 当您定义Sharp时,您尚未定义sharp。您应该可以通过将其更改为Sharp.gravity.northeast来消除错误,但我认为更好的想法是将需求更改为:

const sharp = require('sharp');

因此您的代码将与文档相匹配。这意味着您需要使用大写的“S”更改代码中的位置。例如,Sharp(data.Body)需要成为sharp(data.Body)