Search code examples
javascriptrgbuint8array

Manipulate RGBA Javascript


In Javascript i have a Uint8Array() RGBA of image, here is console.log of this :

enter image description here

Here is image with rgba array as a string in HTML:

enter image description here

Is that possible to manipulate this array, to ex. change colors? Thanks for help!


Solution

  • Here's a JS algorithm of plotting a pixel to this kind of array:

    function changeColor(x, y, c)
    {
       colorArray[(x * 4) + (y * (imageWidth * 4))] = c.r;
       colorArray[(x * 4) + (y * (imageWidth * 4)) + 1] = c.g;
       colorArray[(x * 4) + (y * (imageWidth * 4)) + 2] = c.b;
       colorArray[(x * 4) + (y * (imageWidth * 4)) + 3] = c.a;
    }
    

    where x and y are the coordinates of the pixel you want to change, imageWidth being the width of the image this array produces, c being the colour you want to change the pixel to, and colorArray is the array itself.