The best performance improvement is the transition from the nonworking state to the working state. --John Ousterhout
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 .NET Color to Hex String

By steve on January 09, 2007.
Updated on January 22, 2012.
Viewed 40,850 times (45 times today).
Article TypesLanguage ElementsLanguagesTechnologiesTechnologiesTechnologies
SnippetConversionsC#.NETCSSHTML

Summary

Contents

For a long time I had a fairly complicated way of converting the .NET Color object to a string such as #F782AB. 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.

Color c = Color.Red;
string strColor = System.Drawing.ColorTranslator.ToHtml(c);

Pretty simple isn't it. Don't you just love these little .NET niceties that you can never find when you want 'em?

So before I figured that out, it worked something like this. Note that lblOutput is a Label control on my ASP.NET page.

Example: How to use the conversion method

Contents
public void TestColorToHexString()
{
   Color c1 = Color.White;
   Color c2 = Color.Black;
   Color c3 = Color.LightGoldenrodYellow;
   Color c4 = Color.Gold;

   lblOutput.Text = c1.Name + " =  " 
      + Snippets00002.ColorToHexString(c1) + "<br>";
   lblOutput.Text += c2.Name + " =  " 
      + Snippets00002.ColorToHexString(c2) + "<br>";
   lblOutput.Text += c3.Name + " =  " 
      + Snippets00002.ColorToHexString(c3) + "<br>";
   lblOutput.Text += c4.Name + " =  " 
      + Snippets00002.ColorToHexString(c4) + "<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
White = FFFFFF
Black = 000000
LightGoldenrodYellow = FAFAD2
Gold = FFD700

Here's the class:

The C# Class:

Contents
namespace Cambia.CoreLib
{
   using System;
   using System.Drawing;

   /// <summary>
   /// Useful C# snippets from CambiaResearch.com
   /// </summary>
   public class Snippets00002
   {
      #region -- Data Members --
      static char[] hexDigits = {
         '0', '1', '2', '3', '4', '5', '6', '7',
         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
      #endregion

      public Snippets00002()
      {
      }

      /// <summary>
      /// Convert a .NET Color to a hex string.
      /// </summary>
      /// <returns>ex: "FFFFFF", "AB12E9"</returns>
      public static string ColorToHexString(Color color) 
      {
         byte[] bytes = new byte[3];
         bytes[0] = color.R;
         bytes[1] = color.G;
         bytes[2] = color.B;
         char[] chars = new char[bytes.Length * 2];
         for (int i = 0; i < bytes.Length; i++) 
         {
            int b = bytes[i];
            chars[i * 2] = hexDigits[b >> 4];
            chars[i * 2 + 1] = hexDigits[b & 0xF];
         }
         return new string(chars);
      }


   }
}
Back to Top

User Comments (11)

Posted 2007 Mar 22 10:43 AM. reply
Hehe. Yeah. You save me a lot of work. I didn't know about ColorTranslator. :D

Szymon
Reply 2007 Mar 22 12:20 PM by steve. reply
Glad I could help. As you can see from the article. I didn't know about it for a long time as well!
Replied 2007 Mar 26 07:14 AM by Bee. reply
Do you call this code ? You scratched your head through the legs :) I really hope not the etire library is like that. Check this:

	public static string ColorToHexString( Color oColor )
	{
		return string.Format( "#{0}{1}{2}", oColor.R.ToString( "x" ),
 			oColor.G.ToString( "x" ), oColor.B.ToString( "x" ) );
	}
Reply 2007 Mar 26 22:05 PM by steve. reply
You missed the first part of the article, Bee. You're commenting on the old method. If you'll look at the first code segment in the article you'll see that the new method is shorter and simpler than yours.
Replied 2007 Oct 31 11:29 AM by Brian. reply
There is a problem with ColorTranslator, though. If you are using a control that allows selection of the system colors (Control, ControlDark, etc.), it'll still return a name. If you absolutely need a hex value (as I did in one case), you need Bee's method. However, it can be better expressed like this:

return String.Format( "#{0:x}{1:x}{2:x}", color.R, color.G, color.B );
Replied 2007 Oct 31 13:09 PM by Brian. reply
Oops. This ensures two digits for each value (so #0000FF isn't formatted as "#00FF"):

return String.Format( "#{0:x2}{1:x2}{2:x2}", color.R, color.G, color.B );
Posted 2008 Mar 17 14:04 PM. reply
Thanks. Saved me a lot of time with this.

Baal
Replied 2008 Mar 17 14:13 PM by Baal. reply
Also, the first one liner doesn't work for me because it produces 8 digit colour name. It normally adds 00 at the end of the 6 digit hex number hence crashing my application. Your Colour class does great job though.
Replied 2008 Mar 17 14:34 PM by Baal. reply
Also, the first one liner doesn't work for me because it produces 8 digit colour name. It normally adds 00 at the end of the 6 digit hex number hence crashing my application. Your Colour class does great job though.
Posted 2008 Sep 30 10:26 AM. reply
ColorTranslator.ToHtml may return the name of the color (red, blue, etc).

Converting from the integer value of a color to a hex string may give you an 8 character string (A R G B), I want a 6 character string (R G B).

I used: ColorHexString = MyColor.ToArgb().ToString("X").Substring(2, 6);
it converts the color to an integer, then an 8 character hexstring, then a substring with the last 6 Hex characters.

To go back from this string to a color
I used: MyColor = ColorTranslator.FromHtml('#' + ColorHexString);

Thanks for the help Steve
I hadn't seen the ColorTranslator before your article

Ron
Posted 2009 Mar 12 19:46 PM. reply
Uh, how about this:


int argb = int.Parse("ff" + color.Substring(1,color.Length-1), System.Globalization.NumberStyles.HexNumber);
return System.Drawing.Color.FromArgb(argb);


Rule of thumb: .NET has pretty much a solution for any kind of common problem built in, whenever you have to resort to string parsing and concatenating, you are usually doing something terribly wrong.

-- georg

BioGeorg
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.