Search code examples
colorsprocessing

Accessing each color channel of a color() in Processing 3


In Processing 3, given a variable of type color which stores a color, how would one access each individual color channel?

For example, given the following code:

color c = color(200, 100, 50);
int r, g, b;

I want to extract each of the R, G, and B values from c and store them in r, g, and b respectively, such that:

r == 200
g == 100
b == 50

The Processing 3 reference for color() does not outline any methods of extracting these color channels (see https://processing.org/reference/color_.html).

Any help is appreciated.


Solution

  • java.awt.Color has methods specifically to get each component

    int a = color.getAlpha();
    int r = color.getRed();
    int g = color.getGreen();
    int b = color.getBlue();
    

    If using BufferedImage, using a bitmask may be easier

    int c = color.getRGB(); //or image.getRGB(x, y)
    int a = (c & 0xFF000000) >> 24;
    int r = (c & 0xFF0000) >> 16;
    int g = (c & 0xFF00) >> 8;
    int b = c & 0xFF;