-1

I am building a chrome extension that can read web pages images' rgb into separate arrays. However, there are some zeros from no where in the middle of each array(though the first few pixels' rgb readings are correct). Suspicious 0s. All my image's size are (w:199; H:252) and I just found that there are 198 RGB shown normally in imagedata, but then it is followed by 252 0s. Feel like i did the onload thing right. Can anyone help me figure out the problem?

function readImage(image) {

    var img = new Image();
    img.onload = function () {
        var c = document.createElement('canvas');
        c.height = image.naturalHeight;
        c.width = image.naturalWidth;
        var ctx = c.getContext('2d');
        ctx.drawImage(img, 0, 0);
        console.log("height : " + c.height + "weight: " + c.width);
        var imageData = ctx.getImageData(0, 0, c.height, c.width);
        var pix = imageData.data;
        for (var i = 0, n = pix.length; i < n; i += 4) {
            var alpha = pix[i + 3];
            pix[i + 3] = pix[i + 2];
            pix[i + 2] = pix[i + 1];
            pix[i + 1] = pix[i];
            pix[i] = alpha;
        }      
        console.log("imgaeData = " +pix);
        console.log("raw buffer length= " + pix.length);       
    }
    img.src = image.src;
}
Kaiido
  • 123,334
  • 13
  • 219
  • 285
ykeeky
  • 1
  • 1

1 Answers1

0

Typo: You have inverted width and height in your call to getImageData:

var imageData = ctx.getImageData(0, 0, c.height, c.width);

should be

var imageData = ctx.getImageData(0, 0, c.width, c.height);
Kaiido
  • 123,334
  • 13
  • 219
  • 285