3

In C#, how can I convert a Color object into a byte value?

For example, the color #FFF would be converted to the value 255.

Donut
  • 110,061
  • 20
  • 134
  • 146
Wajahat Kareem
  • 325
  • 2
  • 4
  • 14
  • 2
    Did you not find [this](http://stackoverflow.com/q/982028/1945651) when you Googled? It's the first match when I search for "convert html color to .net color". – JLRishe Jan 30 '13 at 10:31
  • The below answers suggesting ColorConverter.ConvertFromString() may be preferable though. – JLRishe Jan 30 '13 at 10:34
  • I have a color variable in c# and i want it to be converted to bytes value. and thank you for negative points i wont post more question here. – Wajahat Kareem Jan 30 '13 at 10:35
  • What color system are you using where colors are represented by a single 8-bit value? I'm not one of the people who downvoted you BTW. – JLRishe Jan 30 '13 at 10:35
  • If you want the byte values of the colors, you need only access `color.R`, `color.G`, and `color.B`. This will give you three bytes, though, not just one. – JLRishe Jan 30 '13 at 10:39

4 Answers4

9

You can get the byte values of a .NET Color object with:

byte red = color.R;
byte green = color.G;
byte blue = color.B;

That gives you 3 bytes. I don't know how you expect to get a single byte value. Colors are (AFAIK) almost never represented by single bytes.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
2

You could use the ColorTranslator.FromHtml function:

Color color = ColorTranslator.FromHtml("#FFF");
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

You can use ConvertFromString() method from ColorConverter class.

Attempts to convert a string to a Color.

Return Value
Type: System.Object
A Color that represents the converted text.

ColorConverter c = new ColorConverter();
Color color = (Color)c.ConvertFromString("#FFF");
Console.WriteLine(color.Name);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
1

Try this,

string colorcode = "#FFFFFF00";
int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);

also see this How to get Color from Hexadecimal color code using .NET?

Community
  • 1
  • 1
sajanyamaha
  • 3,119
  • 2
  • 26
  • 44