【问题标题】:Converting 2d to 1d array and image output. weird results将 2d 转换为 1d 数组和图像输出。奇怪的结果
【发布时间】: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


    【解决方案1】:

    好的。所以事实证明上面的代码是正确的,我正在使用一个名为sharp的npm模块进行转换。并将选项设置为 3 个通道而不是 4 个(忘记了 alpha),所以现在可以解释漂移。我很困惑。但我相信上面的代码是正确的。因为它在更改后现在按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-29
      • 2022-01-17
      • 1970-01-01
      • 2021-05-27
      • 2019-12-10
      • 2020-01-08
      • 1970-01-01
      • 2017-09-11
      相关资源
      最近更新 更多