Search code examples
node.jsimagenode-canvas

Extract rgba data from image


I am looking for a way to extract all the rgba data of an image.

I came across the getImageData() method from the module canvas and for a 10x10 in my case it returns an array only with zero. Below is how I extract the data right now. Any ideas, thank you

fs.readFile(__dirname + '/image.jpg', function(err, data) {
    if (err) throw err;
    var img = new Canvas(10, 10)   
    img.src = data;
    var c = img.getContext('2d');
    var imgData = c.getImageData(0, 0, img.width, img.height);
})

Solution

  • As I mentioned in my final comment, I believe the root issue is that fs.readFile is returning you raw data, which is of no use for the canvas' src attribute. I think the below will work, but I will confess I haven't tested it.

    fs.readFile(__dirname + '/image.jpg', function(err, data) {
        if (err) throw err;
        var img = new Canvas(10, 10)
       img.src = 'data:image/jpeg;base64,'+ data.toString('base64');
       var c = img.getContext('2d');
       var imgData = c.getImageData(0, 0, img.width, img.height);
    })