There's no sense being exact about something if you don't even know what you're talking about. --John von Neumann

Convert Hex String to .NET Color

Summary

For a long time I had a fairly complicated way of converting a hex string like #F782AB to a .NET color object. Since then some of you have informed me of a much easier way. I'll show you the easy way first and then include the longer method below.

string xCol = "#FF00DD";
Color c = System.Drawing.ColorTranslator.FromHtml(xCol);

Simple, right? Well, before I learned about that little trick here are some hoops and barrels I jumped through to make this happen. Maybe there's something useful in there from a purely tautological point of view. Not that I know what tautological means...that is to say, not that I know the definition of that particular word...

Example: How to use the conversion method
public void TestHexStringToColor()
{
   // invent some hex colors
   string[] h = new string[4];
   h[0] = "#FFFFFF";
   h[1] = "#000000";
   h[2] = "#FFFF00";
   h[3] = "#ABC19D";

   // convert the hex values to colors
   Color[] colors = new Color[4];
   colors[0] = Snippets00001.HexStringToColor(h[0]);
   colors[1] = Snippets00001.HexStringToColor(h[1]);
   colors[2] = Snippets00001.HexStringToColor(h[2]);
   colors[3] = Snippets00001.HexStringToColor(h[3]);

   // print the results
   lblOutput.Text = "";
   for (int i=0; i<h.Length; i++)
   {
      lblOutput.Text += h[i] + " =  " 
         + colors[i].Name + ", Red=" + colors[i].R.ToString()
         + ", Green=" + colors[i].G.ToString()
         + ", Blue=" + colors[i].B.ToString()
         + "<br>";
   }

}

If you run the previous method you'll get the following output displayed in the Label control on the aspx page.

Example: Output
#FFFFFF = ffffffff, Red=255, Green=255, Blue=255
#000000 = ff000000, Red=0, Green=0, Blue=0
#FFFF00 = ffffff00, Red=255, Green=255, Blue=0
#ABC19D = ffabc19d, Red=171, Green=193, Blue=157

Here's the class:

namespace Cambia.CoreLib
{
   using System;
   using System.Drawing;
   using System.Text.RegularExpressions;

   /// <summary>
   /// Useful C# snippets from CambiaResearch.com
   /// </summary>
   public class Snippets00001
   {

      public Snippets00001()
      {
      }

      /// <summary>
      /// Convert a hex string to a .NET Color object.
      /// </summary>
      /// <param name="hexColor">a hex string: "FFFFFF", "#000000"</param>
      public static Color HexStringToColor(string hexColor)
      {
         string hc = ExtractHexDigits(hexColor);
         if (hc.Length != 6)
         {
            // you can choose whether to throw an exception
            //throw new ArgumentException("hexColor is not exactly 6 digits.");
            return Color.Empty;
         }
         string r = hc.Substring(0, 2);
         string g = hc.Substring(2, 2);
         string b = hc.Substring(4, 2);
         Color color = Color.Empty;
         try
         {
            int ri 
               = Int32.Parse(r, System.Globalization.NumberStyles.HexNumber);
            int gi 
               = Int32.Parse(g, System.Globalization.NumberStyles.HexNumber);
            int bi 
               = Int32.Parse(b, System.Globalization.NumberStyles.HexNumber);
            color = Color.FromArgb(ri, gi, bi);
         }
         catch
         {
            // you can choose whether to throw an exception
            //throw new ArgumentException("Conversion failed.");
            return Color.Empty;
         }
         return color;
      }
      /// <summary>
      /// Extract only the hex digits from a string.
      /// </summary>
      public static string ExtractHexDigits(string input)
      {
         // remove any characters that are not digits (like #)
         Regex isHexDigit 
            = new Regex("[abcdefABCDEF\\d]+", RegexOptions.Compiled);
         string newnum = "";
         foreach (char c in input)
         {
            if (isHexDigit.IsMatch(c.ToString()))
               newnum += c.ToString();
         }
         return newnum;
      }

   }
}
 

Version: 6.0.20200920.1535