javascript ImageData typed array read whole pixel?

本小妞迷上赌 提交于 2020-01-01 04:27:05

问题


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!


回答1:


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!



回答2:


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



来源:https://stackoverflow.com/questions/16679158/javascript-imagedata-typed-array-read-whole-pixel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!