Search code examples
node.jsimagemagickgraphicsmagick

Get image pixels using graphicsmagick


Currently I'm using pngjs, like described in this answer, but I want to see how to get the pixels of an image using GraphicsMagick.

I'm using gm as wrapper for GraphicsMagick. I couldn't find any information how to get the image pixels.

I would like to have something like:

myImg.getPixel(x, y, function (err, pixel) {
   // pixel: { r: ..., g: ..., b: ..., a: ... }
});

I'm wondering if toBuffer would help:

gm('img.jpg')
  .resize(100, 100)
  .toBuffer('PNG',function (err, buffer) {
    if (err) return handle(err);
    console.log('done!');
  })

Having the buffer, maybe I'm able to calculate somehow the pixel colors...

What is the easiest way to get the pixel info (r, g, b, a) at given coordinates (x, y) using graphicsmagick?


Solution

  • Using the pngjs library you can parse the PNG buffer obtained from GraphicsMagick:

    const PNG = require("pngjs").PNG
        , gm = require("gm")
        ;
    
    let img = gm("path/to/image.png");
    
    // Get the PNG buffer
    img.toBuffer("PNG", (err, buff) => {
        if (err) { ... }
    
        // Get the image size
        img.size((err, size) => {
          if (err) { ... }
    
          // Parse the PNG buffer
          let str = new PNG();
          str.end(buff);
    
          // After it's parsed...
          str.on("parsed", buffer => {
            // Get some pixel from the image
            let x = 27
              , y = 9
              ;
    
            let idx = (size.width * y + x) << 2
              , rgb = {
                  r: buffer[idx]
                , g: buffer[idx + 1]
                , b: buffer[idx + 2]
                }
              ;
          });
          str.on("error", ...);
        });
    });