How to convert color name to the corresponding hexadecimal representation?

11,515

Solution 1

You're half way there. Use .ToArgb to convert it to it's numberical value, then format it as a hex value.

int ColorValue = Color.FromName("blue").ToArgb();
string ColorHex = string.Format("{0:x6}", ColorValue);

Solution 2

var rgb = color.ToArgb() & 0xFFFFFF; // drop A component
var hexString = String.Format("#{0:X6}", rgb);

or just

var hexString = String.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);

Solution 3

{
    Color color = Color.FromName("blue");
    byte g = color.G;
    byte b = color.B;
    byte r = color.R;
    byte a = color.A;
    string text = String.Format("Color RGBA values: red:{0x}, green: {1}, blue {2}, alpha: {3}", new object[]{r, g, b, a});

// seriously :) this is simple:

    string hex = String.Format("#{0:x2}{1:x2}{2:x2}", new object[]{r, g, b}); 

}

Solution 4

Ahmed's answer is close, but based on your comment, I'll just add a little more.

The code that should make this work is:

Color color = Color.FromName("blue");
string myHexString = String.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);

Now you can do whatever you want with the string myHexString.

Share:
11,515
Jack
Author by

Jack

Computer lover. :-) -- I'm not a native speaker of the english language. So, if you find any mistake what I have written, you are free to fix for me or tell me on. :)

Updated on June 05, 2022

Comments

  • Jack
    Jack almost 2 years

    For example:

    blue 
    

    converts to:

    #0000FF
    

    I wrote it as:

    Color color = Color.FromName("blue");

    But I don't know how to get the hexadecimal representation.

  • Ahmed Masud
    Ahmed Masud over 12 years
    each of color.G; color.B ; color.R and color.A contain the bytes, combine them as you see fit :) ... string hex = String.Format("#{0}{1}{2}", new object[]{r, g, b});
  • Steve Danner
    Steve Danner over 12 years
    +1 I've realized my answer only works half the time, where this should be perfect.
  • Jim Balter
    Jim Balter over 12 years
    It's not "perfect" since it yields "#FF0000FF" rather than "#0000FF". Also, local variables should not start with uppercase.
  • Hand-E-Food
    Hand-E-Food over 12 years
    The leading FF is the alpha channel or opacity. While that may not be relevant for HTML, it's perfectly legal in other situations. You can remove it by using ColorValue & 0xFFFFFF.
  • Jim Balter
    Jim Balter over 12 years
    If you intend to include alpha, then that should be x8, not x6.