javascriptnode.jsjimp

JavaScript - Get RGBA values from bitmap buffer


Hello I'm using NodeJs and a package named "Jimp".

I'm trying to get the Red, Green, Blue, and Alpha values for each pixel but am having trouble.

Here's my code:

Jimp.read("https://i.imgur.com/eOu89DY.png").then((image) => {


console.log(image)

for (var y = 0; y < image.bitmap.height; y = y + 3) {
  for (var x = 0; x < image.bitmap.width; x = x + 3) {


  //--Returns the whole bitmap buffer
  console.log(red)
  var red = image.bitmap.data;

  }
}

and here's the example usage from https://www.npmjs.com/package/jimp :

image.scan(0, 0, image.bitmap.width, image.bitmap.height, function(x, y, idx) {
  // x, y is the position of this pixel on the image
  // idx is the position start position of this rgba tuple in the bitmap Buffer
  // this is the image

  var red = this.bitmap.data[idx + 0];
  var green = this.bitmap.data[idx + 1];
  var blue = this.bitmap.data[idx + 2];
  var alpha = this.bitmap.data[idx + 3];

  // rgba values run from 0 - 255
  // e.g. this.bitmap.data[idx] = 0; // removes red from this pixel
});

Using my code, how could I get the red, green, blue values using variables from the buffer? How do I define IDX like the example usage from the npmjs site???


Solution

  • If you look down a little in the linked page.

    Alternatively, you can manipulate individual pixels using the following these functions:

    image.getPixelColor(x, y); // returns the colour of that pixel e.g. 0xFFFFFFFF
    

    ... ...

    Two static helper functions exist to convert RGBA values into single integer (hex) values:

    Jimp.rgbaToInt(r, g, b, a); // e.g. converts 255, 255, 255, 255 to
    Jimp.intToRGBA(hex); // e.g. converts 0xFFFFFFFF to {r: 255, g: 255, b: 255, a:255}