public static Color? HexToColor(this string hex)
{
if (hex.IsNullOrEmpty() || !hex.IsHexcode())
return null;
int red, green, blue = 0;
try
{
if (hex.Length == 3)
{
red = int.Parse(hex.Substring(0, 1), System.Globalization.NumberStyles.AllowHexSpecifier);
green = int.Parse(hex.Substring(1, 1), System.Globalization.NumberStyles.AllowHexSpecifier);
blue = int.Parse(hex.Substring(2, 1), System.Globalization.NumberStyles.AllowHexSpecifier);
}
else if (hex.Length == 6)
{
red = int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
green = int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
blue = int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
}
else
return null;
}
catch
{
return null;
}
if (red < 0 || red > 255)
return null;
if (green < 0 || green > 255)
return null;
if (blue < 0 || blue > 255)
return null;
return Color.FromArgb(red, green, blue);
}
public static string ColorToHex(this Color clr)
{
int red = clr.R;
int green = clr.G;
int blue = clr.B;
string colorHex = "#";
colorHex += String.Format("{0:X02}", red);
colorHex += String.Format("{0:X02}", green);
colorHex += String.Format("{0:X02}", blue);
return colorHex;
}