How to get the color from a hexadecimal color code using .NET

By FoxLearn 11/20/2024 6:20:31 AM   197
To get the color from a hexadecimal color code in .NET, you can use the System.Drawing.ColorTranslator class or directly parse the value using methods provided by the .NET framework.

The ColorTranslator.FromHtml method allows you to convert a hexadecimal color code to a System.Drawing.Color object.

For example:

string hexColor = "#FFDFD991"; // Hexadecimal color code
Color color = ColorTranslator.FromHtml(hexColor); // ARGB=(255, 223, 217, 145)

If you prefer to extract the RGB values manually.

For example:

hexColor = hexColor.TrimStart('#');

if (hexColor.Length == 6)
{
    int rgb = Convert.ToInt32(hexColor, 16);
    int r = (rgb >> 16) & 0xFF;
    int g = (rgb >> 8) & 0xFF;
    int b = rgb & 0xFF;
    Console.WriteLine($"RGB: {r}, {g}, {b}");
}
else if (hexColor.Length == 8)
{
    int argb = Convert.ToInt32(hexColor, 16);
    int a = (argb >> 24) & 0xFF;
    int r = (argb >> 16) & 0xFF;
    int g = (argb >> 8) & 0xFF;
    int b = argb & 0xFF;
    Console.WriteLine($"ARGB: {a}, {r}, {g}, {b}");
}

If you're using WPF, you can use System.Windows.Media.Color:

For example:

string hexColor = "#FFDFD991"; // Hexadecimal color code with alpha channel
// Use ColorConverter to parse the hex color
Color color = (Color)ColorConverter.ConvertFromString(hexColor);
Console.WriteLine($"ARGB: {color.A}, {color.R}, {color.G}, {color.B}");

The ColorConverter.ConvertFromString method can handle hexadecimal color codes with alpha channels.

System.Windows.Media.Color is part of WPF, so make sure you reference PresentationCore.dll and WindowsBase.dll in your project.