简体   繁体   English

使用 Node.js 在现有 PNG 上写入文本

[英]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.我正在尝试创建一个简单的动态徽章 (png) 以嵌入静态页面以了解我的应用程序的状态。

I'd like so to use an existing PNG image and write on it some text with Node.js.我想使用现有的 PNG 图像并使用 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.我发现了很多库,但它们都使用 Imagemagick 或 Cairo 作为本机依赖项,我想避免在服务器上安装任何其他东西。

I've then found lwip, but I can't really understand how to write text on an image with it.然后我找到了 lwip,但我真的不明白如何用它在图像上写文字。 How can I do?我能怎么做?

You could use Jimp . 你可以使用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.如果你想使用ttf文件,你可以使用gm这也会自动对齐文本,这样你就不必跟踪你的字母大小/位置。

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');
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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