代码之家  ›  专栏  ›  技术社区  ›  Nicola Peluchetti

在AWS中的现有图像上写入自定义文本

  •  1
  • Nicola Peluchetti  · 技术社区  · 6 年前

    我需要能够写一些自定义的文本在我的图像,这是存储在S3。在AWS生态系统中,最好的方法是什么? 如果可能的话,我希望避免启动服务器并在其上运行PHP或节点,我只希望使用lambda函数或类似的函数。

    1 回复  |  直到 6 年前
        1
  •  2
  •   bwest    6 年前

    在lambda上通过node.js使用imagemagick。很多人都这样做了。下面是一个很好的例子: https://tech.mybuilder.com/memes-as-a-service-using-lambda-serverless-and-imagemagick/

    lambda函数如下所示:

    'use strict';
    
    const gm = require('gm').subClass({ imageMagick: true });
    const fs = require('fs');
    
    const { IMAGES_DIR, TEXT_SIZE, TEXT_PADDING } = process.env;
    
    const parseText = text => (text || '').toUpperCase();
    const getImages = () => fs.readdirSync(IMAGES_DIR);
    const parseImage = image => getImages().find(file => file.indexOf(image) === 0);
    const random = arr => arr[Math.floor(Math.random() * arr.length)];
    const randomImage = () => random(getImages());
    
    module.exports.meme = (event, context, callback) => {
      const input = event.queryStringParameters || {};
    
      const top = parseText(input.top);
      const bottom = parseText(input.bottom);
      const image = parseImage(input.image) || randomImage();
    
      const meme = gm(`${IMAGES_DIR}${image}`);
    
      meme.size(function (err, { height }) {
        meme
          .font('./impact.ttf', TEXT_SIZE)
          .fill('white')
          .stroke('black', 2)
          .drawText(0, -(height / 2 - TEXT_PADDING), top, 'center')
          .drawText(0, height / 2 - TEXT_PADDING, bottom, 'center')
          .toBuffer(function (err, buffer) {
            callback(null, {
              statusCode: 200,
              headers: { 'Content-Type': 'image/jpeg' },
              body: buffer.toString('base64'),
              isBase64Encoded: true,
            });
          });
      });
    };