Cambia Research - Supporting the Microsoft .NET Developer Community Supporting the Microsoft .NET Developer Community  

     | Home  | Articles  | Categories  | Coders  | Search  | Submit  | Contact Us    
Computers are good at following instructions, but not at reading your mind. --Donald Knuth

Share Your Knowledge! -- Create and submit your articles the easy way with WebWriter.

Updated:06:34 PM CT Jan 09, 2007
Posted:06:05 PM CT Jan 09, 2007

Convert Hex String to .NET Color

Author: Steve Lautenschlager

SnippetC#.NETCSSHTML

 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:

The C# 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;
      }

   }
}

Add New Comment
Convert Hex String to .NET Color
Jeff Bowden16 Sep 07, 14:09Reply 
Convert Hex String to .NET Color
shai28 Sep 07, 16:58Reply 
Convert Hex String to .NET Color
Tareq23 Jan 08, 4:20Reply 
Convert Hex String to .NET Color
Shokker24 Apr 08, 9:12Reply 
re: Convert Hex String to .NET Color
dev14 Jul 08, 5:24Reply 
Convert Hex String to .NET Color
geedubb17 Sep 08, 12:15Reply 
re: Convert Hex String to .NET Color
geedubb17 Sep 08, 12:16Reply 
Convert Hex String to .NET Color
anton19 Sep 08, 7:33Reply 
Convert Hex String to .NET Color
Yahav05 Oct 08, 3:44Reply 
CR Comments by Cambia Research
advertisement
 
Steve Lautenschlager (steve)
Steve is the founder and creator of Cambia Research. Developing and maintaining the site combines his passions for technology, writing and education.
Steve holds a Ph.D. in particle physics from Duke University, has worked at CERN, the European center for particle physics (where the web was born) and in Microsoft's web division with microsoft.com, msnbc.com and other web properties. Steve is a web consultant specializing in Microsoft.NET technologies. Read more here.


 
Copyright © Cambia Research 2002-2007. All Rights Reserved. steve [ at ] cambiaresearch.com