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