Accessing individual channel values of a color var?

I’m trying to access the individual RGBA channel values of a color variable in Processing.

In p5, it seems like color variables are objects, and they have a property called levels, which is an array, which can spit out individual channel values, like so:

let myColor = color(128, 64, 255);
console.log(myColor.levels[0]); // prints red channel value (128)

But from probing color vars in (Java) Processing, it seems like they’re coded as ints of some kind. I can’t find any documentation on accessing individual color channels in either the Reference or in the Javadoc. Is it possible?

1 Like
Float r = red(myColor);
Float g = green(myColor);
Float b = blue(myColor);
Float br = brightness(myColor);
2 Likes

Facepalm. Thanks. :innocent:

Besides the methods alpha(), red(), green() & blue():




final color
  c = 0x40F0A080, // color as a whole int (32-bit) (4-byte)
  a = (int) alpha(c), // alpha channel
  r = (int) red(c), // red channel
  g = (int) green(c), // green channel
  b = (int) blue(c); // blue channel

println("Color:\t", hex(c));    // 40F0A080
println("Alpha:\t", hex(a, 2)); // 40
println("Red:\t", hex(r, 2));   // F0
println("Green:\t", hex(g, 2)); // A0
println("Blue:\t", hex(b, 2));  // 80

noLoop();

//background(c);
background(r, g, b, a);

We can use bitwise operators in order to grab the 4 channels more performantly:

final color
  c = 0x40F0A080, // color as a whole int (32-bit) (4-byte)
  a = c >>> 030, // alpha channel
  r = c >> 020 & 0xff, // red channel
  g = c >> 010 & 0xff, // green channel
  b = c & 0xff; // blue channel

println("Color:\t", hex(c));    // 40F0A080
println("Alpha:\t", hex(a, 2)); // 40
println("Red:\t", hex(r, 2));   // F0
println("Green:\t", hex(g, 2)); // A0
println("Blue:\t", hex(b, 2));  // 80

noLoop();

//background(c);
background(r, g, b, a);
3 Likes

Sometimes your code is a bit of a mystery, but always concise and to the point! (all good, appreciated!)

Octal literals
Zero fill right shift (search for it on the page).

2 Likes