How to convert System.Drawing.Color to a Html representation (C#)?

by Vitaly Zayko 6. November 2008 17:17

If you are working on some Web-related App then you sooner or later will need to convert a System.Drawing.Color structure to its Html format. Below are three overloaded functions.

        /// <summary>
/// Convert System.Drawing.Color struct to a Html color representation
/// </summary>
/// <param name="color">System.Drawing.Color struct to convert from</param>
/// <returns>Html color format as a string</returns>
public string ToHtmlColor(Color color)
{
   return "#" + color.ToArgb().ToString("x").Substring(2);
}

/// <summary>
/// Convert Red, Green and Blue components to a Html color representation
/// </summary>
/// <param name="r">The Red component value</param>
/// <param name="g">The Green component value</param>
/// <param name="b">The Blue component value</param>
/// <returns>Html color format as a string</returns>
public string ToHtmlColor(int r, int g, int b)
{
   Color color = System.Drawing.Color.FromArgb(r, g, b);
   return "#" + color.ToArgb().ToString("x").Substring(2);
}

/// <summary>
/// Convert ARGB color to a Html color representation
/// </summary>
/// <param name="argb">ARGB color value</param>
/// <returns>Html color format as a string</returns>
public string ToHtmlColor(int argb)
{
   Color color = System.Drawing.Color.FromArgb(argb);
   return "#" + color.ToArgb().ToString("x").Substring(2);
}
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

Comments are closed

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

About the author

Vitaly Zayko

Senior Software Developer / Team Lead / Product Manager

Moscow, Russia