簡體   English   中英

使用 node.js 和 gm 在 AWS Lambda 上為圖像加水印

[英]Watermarking an image on AWS Lambda with node.js and gm

我正在嘗試在 AWS Lambda 函數中調整圖像(從 S3 下載)的大小和水印。

根據 AWS Lambda 的“入門”項目中的示例代碼,調整大小部分運行良好。

現在,我在向文件中添加水印時遇到問題。

在我的本地系統上,我可以這樣做:

gm('martinrose.jpg')
.draw(['image Over 0,0 0,0 wm-bas.png'])
.write('brol.jpg', function(e){
 console.log(e||'done'); 
}); 

它可以毫無問題地工作。

在Lambda環境下,我在上傳到亞馬遜的zip文件中添加了wm-bas.png文件,貌似是我的js代碼找到的(我用lstatSync測試的),但是真正的水印是不行的。

這是我所做的相關部分:

gm(response.Body).size(function(err, size) {
    var scalingFactor = Math.min(
        newSize / size.width,
        newSize / size.height
    );
    var width  = scalingFactor * size.width;
    var height = scalingFactor * size.height;

    var fs = require('fs');
    var stats = fs.lstatSync('wm-bas.png');
    console.log(stats); // this outputs meaningful info, so, the file exists

    var ctx = this.resize(width, height);//this works

    if (shouldWatermark)
    {   
        console.log("trying to watermark");
        ctx = ctx.draw(['image Over 0,0 0,0 wm-bas.png']) //this doesn't work, although the previous log is written
    }

    ctx.toBuffer(imageType, function(err, buffer) 
        {
            if (err) {
                next(err);
            } else {
                next(null, response.ContentType, buffer);
            }
        }
    );
});

我錯過了什么? 為什么這不起作用? 這與我保存在緩沖區而不是文件中的事實有關嗎?

我用這個代碼導入 gm,順便說一句:

 var gm = require('gm')
        .subClass({ imageMagick: true });

您需要將所有node_modulesLambda部署node_modules在一起。 在您的項目中本地安裝您的模塊,並將它們與您的Lambda代碼打包在一起。 另一個非常重要的事實是Amazon Lambda仍然依賴於已安裝的系統庫。 您的Node.js module可能使用的庫可能未安裝在執行Lambda的系統上,您需要將所有內容與Lambda部署一起打包。

請參閱有關Lambda 中的模塊和Node.js 包的官方帖子

我之前使用過“sharp”庫,使用 Nodejs lambda 函數添​​加帶有自定義字體的文本水印。 我在 Medium 上寫了一篇文章,你可以使用 AWS lambda閱讀Watermark

//...
const textedSVG = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" 
xml:lang="en"
height="40"
width="200">
<text
font-family="MyFont"
font-style="italic"
x="0" y="20" font-size="16" fill="#fff">
${process.env.WATERMARK_TEXT}
</text></svg>`);
let imgDst = sharp(origimage.Body);

var buffer = await imgDst
 
  .composite([
    {
      input: textedSVG,
      gravity: "southeast",
    },
  ])
  // Use the Sharp module to resize the image and save in a buffer.
  .resize(width)
  .jpeg({ quality: 70 }) //decrease the image quality
  .toBuffer();
//...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM