Monday, April 19, 2010

.Net Color To HTML Color And Back

Color translation between the .Net color type and the #rrggbb color type is made really easy using the System.Drawing.ColorTranslator class. The calling code itself is simple:

    public string ColorToHtmlStr(System.Drawing.Color c)
    {
        return System.Drawing.ColorTranslator.ToHtml(c);
    }

    public System.Drawing.Color HtmlStrToColor(string HtmlColor)
    {
        try
        {
            return System.Drawing.ColorTranslator.FromHtml(HtmlColor);
        }
        catch
        {
            //Return a default if the HTML color string parameter is invalid
            //The value of the default could be passed as a second parameter.
            return System.Drawing.Color.Black;
        }
    }

No comments:

Post a Comment