Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping an Integer to an RGB color in C#

Tags:

c#

mapping

rgb

So right now I have a number between 0 and 2^24, and I need to map it to three RGB values. I'm having a bit of trouble on how I'd accomplish this. Any assistance is appreciated.

like image 775
Evan Fosmark Avatar asked May 25 '11 21:05

Evan Fosmark


People also ask

How do you convert numbers to RGB?

Hex to RGB conversionGet the 2 left digits of the hex color code and convert to decimal value to get the red color level. Get the 2 middle digits of the hex color code and convert to decimal value to get the green color level.

Are RGB values integers?

RGB color space or RGB color system, constructs all the colors from the combination of the Red, Green and Blue colors. The red, green and blue use 8 bits each, which have integer values from 0 to 255. This makes 256*256*256=16777216 possible colors.

Why do RGB values go from 0 to 255?

It really comes down to math and getting a value between 0-1. Since 255 is the maximum value, dividing by 255 expresses a 0-1 representation. Each channel (Red, Green, and Blue are each channels) is 8 bits, so they are each limited to 256, in this case 255 since 0 is included.

What is the RGB () color function?

Definition and Usage. The rgb() function define colors using the Red-green-blue (RGB) model. An RGB color value is specified with: rgb(red, green, blue). Each parameter defines the intensity of that color and can be an integer between 0 and 255 or a percentage value (from 0% to 100%).


2 Answers

Depending on which color is where, you can use bit shifting to get the individual colors like this:

int rgb = 0x010203;
var color = Color.FromArgb((rgb >> 16) & 0xff, (rgb >> 8) & 0xff, (rgb >> 0) & 0xff);

The above expression assumes 0x00RRGGBB but your colors might be 0x00BBGGRR in which case just change the 16, 8, 0 values around.

This also uses System.Drawing.Color instead of System.Windows.Media.Color or your own color class. That depends on the application.

like image 109
Rick Sladkey Avatar answered Sep 24 '22 18:09

Rick Sladkey


You can do

Color c = Color.FromArgb(someInt);

and then use c.R, c.G and c.B for Red, Green and Blue values respectively

like image 40
Bala R Avatar answered Sep 22 '22 18:09

Bala R