node.jsimage-manipulationjimp

How to mask an image with another b/w image in NodeJS?


So I want to mask this image
image
with this image
image

which will result in this image
image

How to do this in NodeJS?


Solution

  • This can be pretty easy. We just need to use the JIMP package for NodeJS. We can output the image as a file or a buffer to use in canvas too.

    var Jimp = require('jimp');
    Jimp.read(image_1,(err, image) => {
      Jimp.read(image_2,(err1,image1) => {
        image1.resize(image.bitmap.width,image.bitmap.height)
        image.mask(image1,0,0)
        image.write(output_image) //for a file output
    
    //for buffer output
        image.getBufferAsync('image/png'); //for transparent image use image/png
      })
    })