How convert jimp object to image buffer in node?

Roman Shmandrovskyi picture Roman Shmandrovskyi · Mar 16, 2020 · Viewed 10.1k times · Source

So, I use some lib to join countable images in specific way to one single image.

This lib use Jimp library to done it and after all joins return a Jimp object. Like this:

Jimp {
  _background: 0,
  bitmap: {
    data: <Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ... 2359246 more bytes>,
    width: 768,
    height: 768
  }
}

After this joining I need convert this Jimp object to node Buffer object without writing image as file to disc and return Buffer to use it in next steps.

Is it possible? I cant find anything in Jimp DOCs. And when I try write Jimp.bitmap.data to file, this image is corrupted...

Thanks!

Answer

Roman Shmandrovskyi picture Roman Shmandrovskyi · Mar 16, 2020

So, I found solution. There is a method in Jimp lib for this. But no one row from DOCs not describe this. Working solution:

const Jimp = require('jimp');

const img = Jimp.read('img.png');

img.getBuffer(Jimp.MIME_PNG, (err, buffer) => {
  console.log(buffer);
});

And console output:

<Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 03 00 ... 211452 more bytes>

That's works pretty good for me.