0

下面的代码可以正常工作,直到我尝试添加一个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!
  });
4

1 回答 1

3

锐化时,您将其保存在带有大写“S”require的变量中。Sharp您可以在代码中以这种方式使用它,但 sharp.gravity.northeast. 这就是它产生错误的原因——虽然你已经定义了Sharp,但你还没有定义sharp。您应该能够通过将其更改为 来消除错误Sharp.gravity.northeast,但我认为更好的想法是将要求更改为:

const sharp = require('sharp');

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

于 2017-08-06T19:12:50.953 回答