mike-obrien.net Resume Blog Labs
Tuesday, September 18, 2007

Here is a simple method to invert an HTML color:

private static string InvertHTMLColor(string htmlColor)

{

htmlColor = htmlColor.Replace("#", string.Empty).Trim();

if (string.IsNullOrEmpty(htmlColor) || htmlColor.Length != 6)

     throw new ArgumentException("Invalid HTML color.");

return string.Format("#{0}{1}{2}",

     InvertChannel(htmlColor.Substring(0, 2)),

     InvertChannel(htmlColor.Substring(2, 2)),

     InvertChannel(htmlColor.Substring(4, 2)));

}

private static string InvertChannel(string channel)

{

channel = channel.Trim();

if (string.IsNullOrEmpty(channel) || channel.Length != 2)

     throw new ArgumentException("Invalid color channel.");

int a = int.Parse(channel.Substring(0, 1), System.Globalization.NumberStyles.HexNumber);

int b = int.Parse(channel.Substring(1, 1), System.Globalization.NumberStyles.HexNumber);

return (255 - ((16 * a) + b)).ToString("X");

}

.NET | C#