Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 237
Fez Vrasta Avatar asked Oct 10 '14 07:10

Fez Vrasta


People also ask

How do I write to a file in Node JS?

The easiest way to write to files in Node.js is to use the fs.writeFile () API. const content = 'Some content!'; Alternatively, you can use the synchronous version fs.writeFileSync (): const content = 'Some content!'; You can also use the promise-based fsPromises.writeFile () method offered by the fs/promises module:

How do I process images in Node JS?

In this article, you learned how to use sharp methods to process images in Node.js. First, you created an instance to read an image and used the metadata () method to extract the image metadata. You then used the resize () method to resize an image. Afterwards, you used the format () method to change the image type, and compress the image.

What is sharp in Node JS?

Node.js has an ecosystem of libraries you can use to process images, such as sharp, jimp, and gm module. This article will focus on the sharp module. sharp is a popular Node.js image processing library that supports various image file formats, such as JPEG, PNG, GIF, WebP, AVIF, SVG and TIFF.

How do I read an image from a PNG file?

Within the function body, you read the image by calling sharp () which takes the image path as an argument, here with sammy.png. Apart from taking an image path, sharp () can also read image data stored in a Buffer, Uint8Array, or Uint8ClampedArray provided the image is JPEG, PNG, GIF, WebP, AVIF, SVG or TIFF.


1 Answers

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);
    });
like image 145
xstephen95x Avatar answered Oct 13 '22 16:10

xstephen95x