12

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!

leeoniya
  • 1,071
  • 1
  • 9
  • 25

2 Answers2

15

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!
leeoniya
  • 1,071
  • 1
  • 9
  • 25
-3

the buffer length is increased four times because of the retina display, you have to write pixelDensity(1); to avoid this

44 38
  • 1
  • no, it's because 8 bits is used for red, other 8 bits for green and same for blue and alphal. in other words, each pixel is stored in 8x4=32 bits. If you iterate uint8Array you will have x4 elements in the array – cancerbero Jul 02 '19 at 09:27