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.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    2 thoughts on “Converting System.Drawing.Color to hex

    • April 30, 2025 at 10:59 am
      Permalink

      This website, you can find a great variety of online slots from top providers.
      Players can experience classic slots as well as new-generation slots with high-quality visuals and exciting features.
      Whether you’re a beginner or an experienced player, there’s always a slot to match your mood.
      slot casino
      The games are instantly accessible 24/7 and compatible with desktop computers and smartphones alike.
      All games run in your browser, so you can start playing instantly.
      Platform layout is intuitive, making it quick to explore new games.
      Sign up today, and discover the excitement of spinning reels!

    • May 9, 2025 at 6:25 pm
      Permalink

      This resource are presented valuable discount codes for 1x betting.
      These promocodes provide an opportunity to receive extra benefits when playing on the website.
      Every listed promotional codes are always up-to-date to ensure their validity.
      Through these bonuses it is possible to boost your opportunities on the gaming site.
      https://gmsa.com.pk/pages/chto_nughno_imety_v_vidu_vybiraya_okna_iz_pvh_dlya_lodghii.html
      Plus, step-by-step directions on how to redeem bonus codes are offered for maximum efficiency.
      Consider that certain codes may have limited validity, so check them before using.

    Leave a Reply

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