Looping through pixels in an image

前端 未结 2 867
萌比男神i
萌比男神i 2020-12-14 09:56

My project is to input an image into a canvas tag in an HTML page, and then loop through the pixels and RGBA values of the pixels. While looping through the red values,so ev

2条回答
  •  执念已碎
    2020-12-14 10:39

    It's straightforward.

    All the pixel data for a canvas are stored sequentially in an array.

    The first pixel's data occupy array elements #0-3 (red=0/green=1/blue=2/alpha=3).

    The second pixel's data occupy array elements #4-7 (red=4/green=5/blue=6/alpha=7).

    And so on...

    You can load that pixel data by using context.getImageData() and enumerating through the array:

    const imgData = context.getImageData(0, 0, canvas.width, canvas.height);
    const data = imgData.data;
    
    // enumerate all pixels
    // each pixel's r,g,b,a datum are stored in separate sequential array elements
    
    for(const i = 0; i < data.length; i += 4) {
      const red = data[i];
      const green = data[i + 1];
      const blue = data[i + 2];
      const alpha = data[i + 3];
    }
    

    You can also change those array values and then save the array back to the image using context.putImageData().

    // save any altered pixel data back to the context
    // the image will reflect any changes you made
    
    context.putImageData(imgData, 0, 0);
    

    The image will then change according to the changes you made to its pixel array.

    Each pixel contains 4 components red, green, blue, alpha - each of them is number 0-255. The loop starts from top-left to bottom-right.

提交回复
热议问题