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#
Friday, September 28, 2007 10:24:59 PM (GMT Standard Time, UTC+00:00)
Wouldn't the following be better? This also allows strings such as "E" to be converted (E gets converted into F1), uses a simpler conversion and ensures the output is always 2 hex characters long.

private static string InvertChannel(string channel)
{
channel = channel.Trim();

if (string.IsNullOrEmpty(channel) || channel.Length > 2)
throw new ArgumentException("Invalid color channel.");

byte b = byte.Parse(channel, System.Globalization.NumberStyles.HexNumber);
return (0xFF - b).ToString("X2");
}
George
Comments are closed.