Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs create a PNG image with text inside

I'm trying to create a new PNG file to serve back to clients via HTTP (as a response type image/png)

The new file is created by concatenating 3 base PNG files and adding a custom text in the middle of the image.

Problem is, there no built-in library in nodejs to do this. I spent a couple of hours searching and to my surprise, there is no pure JS library to do this. The closest thing is node-pngjs but it lacks the ability to add text. I understand that the text part is complicated since it's somewhat dependent on the OS (fonts installed, DLLs to interface with said fonts, etc).

There are other node modules that are wrappers around imageMagick (gm) and GTK (canvas) but unfortunately imageMagick is 155MB of binaries, and to use canvas you need to compile from source, install python and VS 2010 C++ Express Edition and it does not work on the lastest version of GTK.

The best I got right now is to write an .NET assembly and use it from inside node via edge.js, but that will require both Windows OS and .NET framework on the server.

Again, the complicated part here is adding the text inside the image.

Any suggestion on how to get this working without a sh**load of external dependencies?

like image 476
Nick Avatar asked Mar 24 '14 13:03

Nick


People also ask

How do I save a canvas image in node?

fillRect(0, 0, width, height); // Write the image to file const buffer = canvas. toBuffer("image/png"); fs. writeFileSync("./image. png", buffer);

What is Node canvas?

The node-canvas package is a NodeJS module allows you to create an image programatically. The package uses Cairo 2D graphics library so that you can generate an image in many common formats like JPG, JPEG or PNG.


1 Answers

Yes you are correct, the Node.js support for image processing libraries is weak, most are the wrappers of some CLI application.

The solution that I would use involves PhantomJS which has the canvas and svg support, you could use these features. It's lighter than the other options and does not require external applications to be installed. http://phantomjs.org/quick-start.html

like image 125
Risto Novik Avatar answered Sep 29 '22 17:09

Risto Novik