使用ImageMagick和Google Cloud Functions向图像添加文本

时间:2018-05-16 00:14:42

标签: firebase imagemagick google-cloud-functions

是否有人设法在Google Cloud Functions中使用ImageMagick为图像添加文字?我尝试使用注释,标签,绘图,并没有任何运气。我正在Google云功能网络平台上做所有事情,因此无需移动集成或任何其他内容。

1 个答案:

答案 0 :(得分:0)

TL;DR: Put a TTF file in the same directory as your function is executing in (mine was /user_code), and reference that font directly when you run graphics magick.


Alright, so I seem to have found some manner of solution. My circumstance is not exactly identical to yours, but I was seeing the exact same behavior you were. Rather than spawning a process, I am using the NPM GraphicsMagick wrapper library, GM (https://www.npmjs.com/package/gm). This should be very similar. I am also executing my functions via firebase functions, which is just running Google Cloud Functions, but I do not have access to the configuration so I can't verify that it is just using the defaults. I assume that this uses whatever the default Google Cloud Function image is. In any event, there is clearly some subset of ImageMagick installed on this image, and the normal text functions succeed, but do not modify the image output in any way.

The solution was ultimately to upload a font file with my code to use. System fonts like arial that you would expect to be available did not work. I used https://www.theleagueofmoveabletype.com/league-mono successfully, and used the following code to successfully draw text on Google Cloud Functions:

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

/* ...handler code... */ 

      gm(525, 110, '#ffffffdd')
        .fill('#000000dd')
        .drawCircle(100, 100, 120, 5)
        .font('font.ttf', 20)
        .fill('#00ff00dd')
        .drawText(100, 100, 'graphics')
        .toBase64('png', function(err, base64) {
          if (err != null) {
            throw err;
          }
          console.info(`got base64 encoding: ${base64}`);
          var img = new Buffer(base64, 'base64');

          res.writeHead(200, {
            'Content-Type': 'image/png',
            'Content-Length': img.length,
          });
          res.end(img);
        });

This produced the following output: generated image

I don't know the exact reason this works; I suspect there are no fonts installed in the image. I added alpha to everything because I wasn't certain that things weren't getting written over one another somehow.