Converting System.Drawing.Color to hex

One quick code note to make during building my Azure Cognitive Services demo application. I needed a way how to convert colors of System.Drawing to hex strings that I can use in views. Here is my simple and elegant solution.

To convert Color to hexadecimal string we can use ColorTranslator class from System.Drawing namespace. As I don’t want views to have direct dependencies to System.Drawing classes I wrap ColorTranslator to HtmlHelper extension method.


public static class HtmlExtensions
{
    public static string ColorToHex(this HtmlHelper helper, Color color)
    {
        return ColorTranslator.ToHtml(Color.FromArgb(color.ToArgb()));
    }
}

I convert color to ARGB first as otherwise ColorTranslator returns me the CSS name of color. Converting to ARGB ensures that return value is always the hex string – even for colors with known names.



See also

Leave a Reply

Your email address will not be published. Required fields are marked *