Thursday, June 18, 2009

Converting between HTML Hex color, int, System.Drawing.Color

using System.Drawing;
//...

        [TestMethod]
        public void ColorTest()
        {
            //HTML hex color values and expected int conversions
            Dictionary<string, int> testValues = new Dictionary<string, int> {
            { "#000000", 0 },
            { "#000001", 1 },
            { "#000100", 256 },
            { "#010000", 65536 },
            { "#666666", 6710886 },
            { "#AAAAAA", 11184810 },
            { "#FFFFFF", 16777215 },
            { "#C25454", 12735572 },
            { "#54C254", 5554772 }
            };

            foreach (string htmlColor in testValues.Keys)
            {
                //Drop the #
                string hexString = htmlColor.Substring(1);

                //convert the 6 char hex color value to an int
                //similar to the JavaScript parseInt(hexString, 16) function
                int convertedValue = Convert.ToInt32(hexString, 16);
                int convertedValueAlternative = int.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
                Assert.AreEqual(convertedValue, convertedValueAlternative);

                //convert the int to the 6 char hex color value
                string hexStringFromInt = convertedValue.ToString("X").PadLeft(6, '0');
                Assert.AreEqual(hexString, hexStringFromInt);

                //Check that the converted value matches the expected value
                int expectedValue = testValues[htmlColor];
                Assert.AreEqual(expectedValue, convertedValue);

                //Get the System.Drawing.Color from the hex color value
                Color c = ColorTranslator.FromHtml(htmlColor);
                //Get the hex color value from the System.Drawing.Color
                string htmlHexColor = ColorTranslator.ToHtml(c);
                Assert.AreEqual(htmlColor, htmlHexColor);
            }
        }