Simplicity is prerequisite for reliability. --Edsger W. Dijkstra
Welcome to my blog and project site for Microsoft.NET development.

I've been a full time .NET developer for ten years, but I didn't start my professional life as a programmer ... more
Share/Print this page:

Convert Hex String to .NET Color

By steve on January 09, 2007.
Updated on January 22, 2012.
Viewed 94,262 times (0 times today).
Article TypesLanguage ElementsLanguagesTechnologiesTechnologiesTechnologies
SnippetConversionsC#.NETCSSHTML

Summary

Contents

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

Contents
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

Contents
#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:

Contents
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;
      }

   }
}
Back to Top

User Comments (12)

Posted 2007 Sep 16 14:09 PM. reply
Thanks for keeping the original code around. .net's compact framework does not include the ColorTranslator namespace!

Jeff Bowden
Posted 2007 Sep 28 16:58 PM. reply
Awesome!! thanks man really helped.

shai
Posted 2008 Jan 23 04:20 AM. reply
Thanks a lot .......

Tareq
Posted 2008 Apr 24 09:12 AM. reply
I had the same problem and used the following construction
Color.FromArgb(Int32.Parse(child.InnerText.Replace("#",""),System.Globalization.NumberStyles.HexNumber));

Shokker
Replied 2008 Jul 14 05:24 AM by dev. reply
It works! thanks.
Posted 2008 Sep 17 12:15 PM. reply
You could use this to convert to a hex string from a Color c. You wont need the ColorTranslator class either

string.Format("{0:X}{1:X}{2:X}{3:X}", c.A, c.R, c.G, c.B);

geedubb
Replied 2008 Sep 17 12:16 PM by geedubb. reply
Forgot the # symbol: string.Format("{0:X}{1:X}{2:X}{3:X}", c.A, c.R, c.G, c.B);
Posted 2008 Sep 19 07:33 AM. reply
Very useful thanks!

anton
Posted 2008 Oct 05 03:44 AM. reply
thanks, the ColorTranslator is what I was looking for. :-)

Yahav
Posted 2009 Aug 20 12:36 PM. reply
Could always just use the Drawing.ColorTranslator.FromHtml function instead.

anon
Posted 2011 Oct 06 04:34 AM. reply
[VB.NET]
Dim hex As String = StringFormat("0x{0:X8}", Me.BackColor.ToArgb())
TextBox1.Tex = hex

Oriundo
Posted 2011 Nov 27 07:11 AM. reply
if you want to convert drawing.color object into hex value, try this code: http://www.authorcode.com/how-to-find-out-hex-value-of-a-color-using-vb-net/

hscoder
Post Your Comment
  You may post without logging in or login here.
Display Name: Required.
Email: Required. Will not be shown. Used for identicon.
Comment:
Allowed tags: <quote></quote>, <code></code>, <b></b>, <i></i>, <u></u>, <red></red>
 
   Please type text as shown in the image at left.