How can I get a color from a hexadecimal color code (e.g. #FFDFD991
)?
I am reading a file and am getting a hexadecimal color code. I need to create the
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");
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.
Follow Oded's suggestion if you need to get the color based on the hexadecimal value of the color.
private Color FromHex(string hex)
{
if (hex.StartsWith("#"))
hex = hex.Substring(1);
if (hex.Length != 6) throw new Exception("Color not valid");
return Color.FromArgb(
int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber));
}
The three variants below give exactly the same color. The last one has the benefit of being highlighted in the Visual Studio 2010 IDE (maybe it's ReSharper that's doing it) with proper color.
var cc1 = System.Drawing.ColorTranslator.FromHtml("#479DEE");
var cc2 = System.Drawing.Color.FromArgb(0x479DEE);
var cc3 = System.Drawing.Color.FromArgb(0x47, 0x9D, 0xEE);
You could use the following code:
Color color = System.Drawing.ColorTranslator.FromHtml("#FFDFD991");
Use
System.Drawing.Color.FromArgb(myHashCode);