Zayko in the Net

Personal blog of Vitaly Zayko

NAVIGATION - SEARCH

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

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

Add comment