Overlay Text on an Image Using Jimp in Node.js



Like Image, we can also overlay text on an image using JIMP. This can be used to display brands or copyright information on images. The print() method is used to write text on images. Though Jimp can only support the Bitmap font format (.fnt), but other fonts can be converted into this format to be compatible and used with JIMP.

Syntax

image.print(font, x, y, message);

Definition of print() paramters

  • font – This describes the font passed by the user for writing the text on image.

  • x, y – The coordinates where the file will be placed.

  • message – This is the user defined message which is passed in the print() for printing it on image.

Input Image

Using Node JIMP – GREYSCALE()

Before proceeding to use greyscale() functions, please check that the following statements are already executed for setting up the environment.

  • npm init -y // Initialising the Node environment

  • npm install jimp --save // Installing the jimp dependency

  • Create a textOverlay.js file and copy-paste the following code snippet in it.

  • Use node textOverlay.js to run the code.

Note − The method name should match with the JS file name. Only then it will be able to call the desired method.

Example

const Jimp = require('jimp') ;

async function textOverlay() {
   // Reading image
   const image = await Jimp.read('/home/jimp/tutorials_point_img.jpg');
   // Defining the text font
   const font = await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK);
   image.print(font, 10, 350, 'All copyrights @https://www.tutorialspoint.com');
   // Writing image after processing
   await image.writeAsync('/home/jimp/textOverlay.png');
}

textOverlay();
console.log("Image is processed succesfully");

Output

Updated on: 2021-04-28T06:17:29+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements