简体   繁体   中英

Write text on existing PNG with Node.js

I'm trying to create a simple dynamic-badge (png) to embed in static pages to let know the status of my application.

I'd like so to use an existing PNG image and write on it some text with Node.js.
I've found lot of libraries but all of them use Imagemagick or Cairo as native dependencies, I'd like to avoid to install anything else on the server.

I've then found lwip, but I can't really understand how to write text on an image with it. How can I do?

You could use Jimp . It has a print method:

var Jimp = require("jimp");

var fileName = 'test.png';
var imageCaption = 'Image caption';
var loadedImage;

Jimp.read(fileName)
    .then(function (image) {
        loadedImage = image;
        return Jimp.loadFont(Jimp.FONT_SANS_16_BLACK);
    })
    .then(function (font) {
        loadedImage.print(font, 10, 10, imageCaption)
                   .write(fileName);
    })
    .catch(function (err) {
        console.error(err);
    });

If you want to use a ttf file you can use gm This will also align the text automatically so you don't have to keep track of your letter sizing / location.

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


gm('path/to/image.png')
        .fill("#FFFFFF")
        .font("./font.ttf", 20)
        .drawText(15, 10, "your text", 'southeast') //can be any location
        .write("./output.png", function (err) {
            if (!err) console.log('done');
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM