Cycle through all rgb values

15,992

Solution 1

You can simply use 3 nested loops:

var red, green, blue;

for (red = 0; red <= 255; red++) {
    for (green = 0; green <= 255; green++) {
        for (blue = 0; blue <= 255; blue++) {
            // rgb(red, green, blue)
        }
    }
}

Order:

 R  |  G  |  B
---------------
  0 |   0 |   0
  0 |   0 |   1
  0 |   0 |   2
...............
255 | 255 | 253
255 | 255 | 254
255 | 255 | 255

An alternative is a loop that loops to 256 * 256 * 256 (16777216):

var red, green, blue;

for (var rgb = 0; rgb <= 16777216; rgb++) {
    red   = (rgb >> 16) & 0xFF;
    green = (rgb >> 8) & 0xFF;
    blue  = (rgb) & 0xFF;

    // rgb(red, green, blue)
}

Here the order would be:

 R  |  G  |  B
---------------
  0 |   0 |   0
  1 |   0 |   0
  2 |   0 |   0
...............
253 | 255 | 255
254 | 255 | 255
255 | 255 | 255

The performance won't be as good though, as you'd use a lot of logic.

Solution 2

It could be done with the follwing nested loops.

var r;
var g;
var b;
for ( r = 0; r <= 255; r++ )
{
  for ( g = 0; g <= 255; g++ )
  {
    for ( b = 0; b <= 255; b++)
    {
      // output values of r, g and b
    }
  }
}
Share:
15,992
user3387566
Author by

user3387566

Updated on July 20, 2022

Comments

  • user3387566
    user3387566 almost 2 years

    rgb range of 0-255 for each (red, green and blue) means that there should be 256x256x256 possible rgb colour values.

    How can I loop through and print every single value?

    I don't need a specific order yet I just want to know how to go through and get all values without skipping any.