views:

2767

answers:

5

How can I get Color from a Hex color code(e.g. #FFDFD991)?

I am reading a file and getting Hex color code, I need to create the corresponding System.Windows.Media.Color instance for the Hex color code. Is there any inbuilt method in framework to do this?

+15  A: 

Assuming you mean the HTML type RGB codes (called Hex codes, such as #FFCC66), use the ColorTranslator class:

System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FFCC66");

If, however you are using an ARGB hex code, you can use the ColorConverter class from the System.Windows.Media namespace:

Color col = ColorConverter.ConvertFromString("#FFDFD991") as Color;
Oded
The example code shows 8 hex digits, so this would likely make it ARGB type. In any case: not a HTML color code.
Thorarin
@Thorarin: The example was added after Oded's answer and is likely to be something random OP just typed out.
Mehrdad Afshari
Doesn't look random to me, the alpha channel is fully opaque for example, which is fairly common and not-random :) Also, SO didn't show any revisions on the question when I posted this.
Thorarin
@Thorarin: SO merges all revisions by a single user in a 5 minute time frame. If you edit your post in 5 minutes, it'll show up as a single revision. It's confusing sometimes.
Mehrdad Afshari
I am using System.Windows.Media.Color
viky
A: 

If you mean HashCode as in .GetHashCode(), I'm afraid you can't go back. Hash functions are not bi-directional, you can go 'forward' only, not back.

Edit: Follow Oded's suggestion if you need to get the color based on the hexadecimal value of the color.

Wim Hollebrandse
I have corrected my question
viky
A: 
System.Drawing.Color.FromArgb(myHashCode);

?

herzmeister der welten
Glances over the conversion from hex string to `int`?
Thorarin
Originally the question was asked as "How to get a color from a hash code" which created a lot of confusion in here. ;-)
herzmeister der welten
+2  A: 

If you don't want to use the ColorTranslator, you can do it in easily:

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

The colorcode is just the hexadecimal representation of the argb value.

Hans Kesting
+12  A: 

I'm assuming that's an ARGB code... Are you referring to System.Drawing.Color or System.Windows.Media.Color? The latter is used in WPF for example. I haven't seen anyone mention it yet, so just in case you were looking for it:

using System.Windows.Media;

Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");
Thorarin
+1, This is exactly what I was looking for!! thanks
viky