LoginSignup
9
10

More than 5 years have passed since last update.

AWS LambdaでImageMagickによる画像への文字埋め込みで好きなフォントを使う方法

Last updated at Posted at 2017-07-19

LambdaでImageMagickを用いて好きなフォントを使う方法

方法は単純。
TrueTypeFontファイルへのパスをfontに渡してあげるだけ。
なのでデプロイパッケージに好きなフォントのttfファイルを含めてあげればできる。
下にサンプルソース。
(imagemagickのコマンドを使用する、こっちのほうが個人的には楽だった)

const exec = require('child_process').exec;
const aws = require('aws-sdk');
const s3 = new aws.S3({region: "ap-northeast-1"});
const fs = require ('fs');
const uuid = require('uuid');

exports.handler = (event, context, callback) => {
  const dir = `/tmp/${uuid.v4()}`; // 書き込み可能なのは/tmp以下だけ、かつ名前重複でエラー起きるので重複できないようにする。
  const options = [
    "-size 300x300", // 画像のサイズ。変更元をxc:whiteにしているため必要
    "-font ipam.ttf", // TrueTypeFontファイルへのパス。好きなフォントのTTFを使えばよろし。
    "-pointsize 24", // 文字サイズ
    '-fill "#000000"', // 文字色
    "-gravity center", // 文字の基準位置
    '-annotate +0+0 "テスト"' // 文字。基準位置(もしくは左上)からの位置を調整できる。
  ];
  exec(`mkdir ${dir} && convert ${options.join(" ")} xc:white ${dir}/image.png`, (err, stdout, stderr) => {
    if (err) {
      callback(stderr.split("\n"));
      return;
    }
    s3.putObject({
      Bucket: "",
      Key: "",
      Body: fs.createReadStream(`${dir}/image.png`),
      ContentEncoded: 'base64',
      ContentType: 'image/png'
    }, (ex) => {
      if (ex) {
        callback(ex);
        return;
      }
      callback(null, "success");
    });
  });
};
9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10