Reputation: 51
Has anyone managed to get adding text to images working using ImageMagick within Google Cloud Functions? I tried using annotate, label, draw and had no luck with any. I am doing everything on the Google Cloud Functions web platform, so no need for mobile integration or anything.
Upvotes: 1
Views: 1207
Reputation: 4977
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:
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.
Upvotes: 1