C# .NET: Convert System.Drawing.Color to HTML color
The System.Drawing.ColorTranslator
class has some static methods that can be used to convert to/from HTML colors and the System.Drawing.Color
object for that color in C# other .NET languages. There are times when this task is necessary, and it’s somewhat of a little known feature within the System.Drawing
namespace.
To convert from an HTML color code to System.Drawing.Color
, use the following:
System.Drawing.ColorTranslator.FromHtml("#F5F7F8");
To convert from System.Drawing.Color
to an equivalent HTML color code, use the following:
System.Drawing.ColorTranslator.ToHtml(c);
Here is a small C# example of how to convert a System.Drawing.Color
to the HTML color format (Hex value or HTML color name value) and back.
// Convert from HTML color
System.Drawing.Color c = System.Drawing.ColorTranslator
.FromHtml("#F5F7F8");
// Convert to HTML color
String strHtmlColor = System.Drawing.ColorTranslator
.ToHtml(c);
Hopefully this helps you with the color code conversions you are needing to perform within your applications.
Related Posts
-
C#: Case-Insensitive String Contains Best Practices
18 Oct 2024 -
C#: Read Text and JSON File Contents into Variable in Memory
18 Jun 2024 -
How to Cast an Int to an Enum in C#
17 Jun 2024