javascript ImageData typed array read whole pixel?
Asked Answered
I

2

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!

Incised answered 21/5, 2013 at 20:43 Comment(0)
I
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!
Incised answered 21/5, 2013 at 21:3 Comment(3)
Is this faster than looping over pixelsNammu
Thank you, this is exactly what I was looking for. Looping over a Uint32Array and comparing the values (without needing to create hashes) is enormously faster for my application.Diaphoresis
Thanks! two ways of iterating compared jsfiddle.net/cancerbero_sgx/05ve439a/13Howund
R
-3

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

Ratoon answered 15/6, 2019 at 12:31 Comment(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 arrayHowund

© 2022 - 2024 — McMap. All rights reserved.