【发布时间】:2021-05-15 02:55:11
【问题描述】:
好的。所以我将二维像素矩阵转换为一维 uint8clampedarray。
class test{
constructor(x,y){
this.width=x;
this.height=y;
this.data = new uInt8ClampedArray(x*y*4)
}
convertMatrixToPixels(){
const IMAGE = Uint8ClampedArray.from(this.data)
//convert a regular 2d js array into a 1d clamped array
let lastNum=-4;//4 away from zero
for (let y = 0; y < this.height; y++) {
for (let x = 0; x < this.width; x++) {
var pos = (((y * (this.width)) + x) * 4)
console.assert(pos==lastNum+4,`weird pos ${pos} and lastNum${lastNum} are not aligned`)
//r
IMAGE[pos] = 0
//g
IMAGE[pos + 1] =0
//b
IMAGE[pos + 2] =0
// and opacity
IMAGE[pos + 3] = 255;
//lastNum recorded for debug
lastNum=Number(pos);
}
}
console.assert(lastNum+4 == this.data.length,`"lastNum, this.data.length${lastNum} is that ${this.data.length}"`)
return IMAGE
}
}
但是,当我执行此代码时,我得到了一系列带。 [1]:https://i.stack.imgur.com/RzDWW.png,对不起(太小了……大的只是伤眼睛)
如果图像太小,则垂直条纹是每个像素列 - 并且按黑色,红色,绿色,蓝色的顺序......这是错误的线索......这一定是某种算错了。
所以我认为这是一种错误的类型,我尝试重新安排迭代的顺序,改变 pos 的计算......但没有骰子。
我期待一张纯黑色的图片,据我所知,我一次迭代所有像素 4,而不是跳跃任何...所以我在哪里有点神秘减一(如果那是错误的)
【问题讨论】:
标签: javascript image math multidimensional-array