Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript ImageData typed array read whole pixel?

So there is are a lot of examples on how to write an entire pixel from a Uint32Array view of the ImageData object. But is it possible to read an entire pixel without incrementing the counter 4 times? From hacks.mozilla.org, writing an rgba pixels looks like this.

var imageData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);

var buf = new ArrayBuffer(imageData.data.length);
var buf8 = new Uint8ClampedArray(buf);
var data = new Uint32Array(buf);

for (var y = 0; y < canvasHeight; ++y) {
    for (var x = 0; x < canvasWidth; ++x) {
        var value = x * y & 0xff;

        data[y * canvasWidth + x] =
            (255   << 24) |    // alpha
            (value << 16) |    // blue
            (value <<  8) |    // green
             value;            // red
    }
}

imageData.data.set(buf8);

ctx.putImageData(imageData, 0, 0);

But, how can I read an entire pixel from a single offset in a 32-bit view of ImageData? Here's what I'm finding confusing, shouldn't the buf32 below have a length of 256/4 = 64?

// 8x8 image
var imgd = ctx.getImageData(0, 0, canvasWidth, canvasHeight),
    buf32 = new Uint32Array(imgd.data);

console.log(imgd.data.length);  // 256
console.log(buf32.length);      // 256  shouldn't this be 256/4 ?

thanks!

like image 224
leeoniya Avatar asked May 21 '13 20:05

leeoniya


1 Answers

figured it out, i need to pass the buffer itself into the Uint32Array constructor, not another BufferView.

var buf32 = new Uint32Array(imgd.data.buffer);
console.log(buf32.length)  // 64 yay!
like image 90
leeoniya Avatar answered Oct 17 '22 08:10

leeoniya