114

Possible Duplicate:
How to get Color from Hex color code using .NET?

I want to convert a string like #FFFFFF to System.Drawing.Color. How do you do that?

Community
  • 1
  • 1
user1531040
  • 2,143
  • 6
  • 28
  • 48

3 Answers3

274
string hex = "#FFFFFF";
Color _color = System.Drawing.ColorTranslator.FromHtml(hex);

Note: the hash is important!

varg
  • 3,446
  • 1
  • 15
  • 17
29

You can do

var color =  System.Drawing.ColorTranslator.FromHtml("#FFFFFF");

Or this (you will need the System.Windows.Media namespace)

var color = (Color)ColorConverter.ConvertFromString("#FFFFFF");
SidAhmed
  • 2,332
  • 2
  • 25
  • 46
13

Remove the '#' and do

Color c = Color.FromArgb(int.Parse("#FFFFFF".Replace("#",""),
                         System.Globalization.NumberStyles.AllowHexSpecifier));
wonea
  • 4,783
  • 17
  • 86
  • 139
codeteq
  • 1,502
  • 7
  • 13
  • 1
    There are options available which do no require the conversion to a numeric value, this is an unnecessary step. The OP states it's a string – freefaller Aug 28 '12 at 09:02
  • 5
    The other solutions are converting the string into a numeric value too, they are just doing it internally. If this is a question of optimization, then performance testing would be required to see how `Color.FromArgb()` w/ `int.Parse()` compare to `ColorConvertor.ConvertFromString()` and `ColorTranslator.FromHtml()`. – jwatts1980 Apr 02 '15 at 17:47
  • Won't that have an alpha value of 0? – Nyerguds Nov 23 '16 at 19:40