【问题标题】:Rotating a 1d RGBA array旋转一维 RGBA 阵列
【发布时间】:2018-05-31 22:30:06
【问题描述】:

我正在使用如下所示的一维像素 RGBA 数组:

pixelArray =[0,0,0,255,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255];

这个pixelArray在绘制时对应的是2个黑色像素和4个白色像素:

BB
WW
WW

我的目标是旋转数组内像素的顺序,使绘制时的图片看起来像

BWW  or WWB
BWW     WWB

这意味着我需要将 pixelArray 转换为

rotatedPixelArray = [0,0,0,255,255,255,255,255,255,255,255,255,0,0,0,255,255,255,255,255,255,255,255,255]

上面的例子只是一个例子。实际的 rgba 可以代表任何图像,长度可能为 100 万+。 我尝试了各种算法like this,并转换为二维数组,然后旋转和展平(确实有效),但我想避免这种情况,因为速度/内存是一个问题。

【问题讨论】:

    标签: javascript arrays rotation p5.js


    【解决方案1】:

    也许这可能有助于 p5.js 进行 90 度旋转(左右)(之前建议的解决方案似乎有一点“不对称”错误):

    function rotateRight(img){
    
      var w = img.width;
      var h = img.height;
      var index, indexr;
      var img2 = createImage(w, h);
    
      img.loadPixels();
      img2.loadPixels();
    
      indexr = 0;
    
      for (let x = 0; x < w; x++) {
    
        for(let y = h - 1; y >= 0; y--) {
    
          index = (x+y*w)*4;
          img2.pixels[indexr] = img.pixels[index];
          img2.pixels[indexr + 1] = img.pixels[index+1];
          img2.pixels[indexr + 2] = img.pixels[index+2];
          img2.pixels[indexr + 3] = img.pixels[index+3];
    
          indexr += 4;
    
        }
      }
    
      img.updatePixels();
      img2.updatePixels();
    
      return img2;
    
    }
    
    
    function rotateLeft(img){
    
      var w = img.width;
      var h = img.height;
      var index, indexr;
      var img2 = createImage(w, h);
    
      img.loadPixels();
      img2.loadPixels();
    
      indexr = 0;
    
      for (let x = w - 1; x >= 0; x--) {
    
        for(let y = 0; y < h; y++) {
    
          index = (x+y*w)*4;
          img2.pixels[indexr] = img.pixels[index];
          img2.pixels[indexr + 1] = img.pixels[index+1];
          img2.pixels[indexr + 2] = img.pixels[index+2];
          img2.pixels[indexr + 3] = img.pixels[index+3];
    
          indexr += 4;
    
        }
      }
    
      img.updatePixels();
      img2.updatePixels();
    
      return img2;
    
    }
    

    【讨论】:

      【解决方案2】:

      所以我想通了,就我而言,它需要向左或向右旋转。我使用的代码如下:

      function rotatePixelArray(pixelArray,w,h) {
        var rotatedArray = [];
      
        for (var x=0;x<w;x++) {
          for(var y=0;y<h;y++) {
            index = (x+y*w)*4;
            rotatedArray.push(pixelArray[index]);
            rotatedArray.push(pixelArray[index+1]);
            rotatedArray.push(pixelArray[index+2]);
            rotatedArray.push(pixelArray[index+3]);
          }
        }
      
        return rotatedArray;
      }
      

      要将其旋转回来,您可以传入切换的 w,h 变量。

      【讨论】:

      • 我试过了,它旋转得很好。唯一的问题是,它在旋转过程中镜像图像,知道如何防止这种情况发生吗?
      猜你喜欢
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      相关资源
      最近更新 更多