Using Custom Font With Jimp In Nodejs

02 Jul 2024 - Syed Muhammad Shahrukh Hussain

This guide help you to utlize custom fonts using Hiero with jimp for editing images on nodejs. These are list of fonts that are supported by jimp.

Brief

Nodejs

Node.jsĀ® is a JavaScript runtime environment that is free, open-source, and cross-platform, enabling developers to build servers, web applications, command-line tools, and scripts.

Jimp

A JavaScript-based image processing library for Node that is entirely written in JavaScript and has no native dependencies.

Hiero

Hiero is a tool for packing bitmap fonts. It stores fonts in the Angel Code format, compatible with BitmapFont in libGDX applications.

Setup

Create a directory for the package or application

mkdir jimp-custom-font

Optionally you can initialize the package, which will create package.json

cd jimp-custom-font
npm init -y

Install jimp package, this will edit the package.json and add dependencies for jimp.

npm install --save jimp

package.json

{
  "name": "jimp-custom-font",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "jimp": "^0.22.12"
  }
}

Create bitmap font .fnt

Using Hiero you can create a new bitmap font which can be used with jimp. Select the font, color and size. Prese Ctrl+B for saving the font. The output will .fnt file and .png file.

Select sansserif size 18 and color black. Save the file sans-serif-18. This will create two files sans-serif-18.fnt and sans-serif-18.png. Copy these file in jimp-custom-font/fonts directory.

Hiero

Template Image

Download the template.png to use with script.

Template

Writing text using jimo

Create index.js: file.

var Jimp = require("jimp");

let template_name = 'template.png'; // image file to edit.
let fnt_sans_serif_18 = "fonts/sans-serif-18.fnt";
let filename = "output.png";
Jimp.read(template_name, (err, template) => {
  if (err) throw err;
      Jimp.loadFont(fnt_sans_serif_18).then((font) => {
  template
    .print(font, 50, 100, "Hello world")
    .write(filename); // save
  });
});

Sources

Output

Output