[c#] How do I get the color from a hexadecimal color code using .NET?

How can I get a color from a hexadecimal color code (e.g. #FFDFD991)?

I am reading a file and am getting a hexadecimal color code. I need to create the corresponding System.Windows.Media.Color instance for the hexadecimal color code. Is there an inbuilt method in the framework to do this?

This question is related to c# wpf colors hex

The answer is


Assuming you mean the HTML type RGB codes (called Hex codes, such as #FFCC66), use the ColorTranslator class:

System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FFCC66");

If, however you are using an ARGB hex code, you can use the ColorConverter class from the System.Windows.Media namespace:

Color col = ColorConverter.ConvertFromString("#FFDFD991") as Color;
//or      = (Color) ColorConverter.ConvertFromString("#FFCC66") ;

in asp.net:

color_black = (Color)new ColorConverter().ConvertFromString("#FF76B3");

You could use the following code:

Color color = System.Drawing.ColorTranslator.FromHtml("#FFDFD991");

I needed to convert a HEX color code to a System.Drawing.Color, specifically a shade of Alice Blue as a background on a WPF form and found it took longer than expected to find the answer:

using System.Windows.Media;

--

System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml("#EFF3F7");
this.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(myColor.A, myColor.R, myColor.G, myColor.B));

There is also this neat little extension method:

static class ExtensionMethods
{
    public static Color ToColor(this uint argb)
    {
        return Color.FromArgb((byte)((argb & -16777216)>> 0x18),      
                              (byte)((argb & 0xff0000)>> 0x10),   
                              (byte)((argb & 0xff00) >> 8),
                              (byte)(argb & 0xff));
    }
}

In use:

Color color = 0xFFDFD991.ToColor();

The three variants below give exactly the same color. The last one has the benefit of being highlighted in the Visual Studio 2010 IDE (maybe it's ReSharper that's doing it) with proper color.

var cc1 = System.Drawing.ColorTranslator.FromHtml("#479DEE");

var cc2 = System.Drawing.Color.FromArgb(0x479DEE);

var cc3 = System.Drawing.Color.FromArgb(0x47, 0x9D, 0xEE);

WPF:

using System.Windows.Media;

//hex to color
Color color = (Color)ColorConverter.ConvertFromString("#7AFF7A7A");

//color to hex
string hexcolor = color.ToString();

If you mean HashCode as in .GetHashCode(), I'm afraid you can't go back. Hash functions are not bi-directional, you can go 'forward' only, not back.

Follow Oded's suggestion if you need to get the color based on the hexadecimal value of the color.


    private Color FromHex(string hex)
    {
        if (hex.StartsWith("#"))
            hex = hex.Substring(1);

        if (hex.Length != 6) throw new Exception("Color not valid");

        return Color.FromArgb(
            int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
            int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
            int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber));
    }

You can see Silverlight/WPF sets ellipse with hexadecimal colour for using a hex value:

your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)

If you want to do it with a Windows Store App, following by @Hans Kesting and @Jink answer:

    string colorcode = "#FFEEDDCC";
    int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
    tData.DefaultData = Color.FromArgb((byte)((argb & -16777216) >> 0x18),
                          (byte)((argb & 0xff0000) >> 0x10),
                          (byte)((argb & 0xff00) >> 8),
                          (byte)(argb & 0xff));

I used ColorDialog in my project. ColorDialog sometimess return "Red","Fhushia" and sometimes return "fff000". I solved this problem like this maybe help someone.

        SolidBrush guideLineColor;
        if (inputColor.Any(c => char.IsDigit(c)))
        {
            string colorcode = inputColor;
            int argbInputColor = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
             guideLineColor = new SolidBrush(Color.FromArgb(argbInputColor));

        }
        else
        {
            Color col = Color.FromName(inputColor);
             guideLineColor = new SolidBrush(col);
        }

InputColor is the return value from ColorDialog.

Thanks everyone for answer this question.It's big help to me.


Use

System.Drawing.Color.FromArgb(myHashCode);

If you don't want to use the ColorTranslator, you can do it in easily:

string colorcode = "#FFFFFF00";
int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);

The colorcode is just the hexadecimal representation of the ARGB value.

EDIT

If you need to use 4 values instead of a single integer, you can use this (combining several comments):

string colorcode = "#FFFFFF00";    
colorcode = colorcode.TrimStart('#');

Color col; // from System.Drawing or System.Windows.Media
if (colorcode.Length == 6)
    col = Color.FromArgb(255, // hardcoded opaque
                int.Parse(colorcode.Substring(0,2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(2,2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(4,2), NumberStyles.HexNumber));
else // assuming length of 8
    col = Color.FromArgb(
                int.Parse(colorcode.Substring(0, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(2, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(4, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(6, 2), NumberStyles.HexNumber));

Note 1: NumberStyles is in System.Globalization.
Note 2: please provide your own error checking (colorcode should be a hexadecimal value of either 6 or 8 characters)


This post has become the goto for anyone trying to convert from a hex color code to a system color. Therefore, I thought I'd add a comprehensive solution that deals with both 6 digit (RGB) and 8 digit (ARGB) hex values.

By default, according to Microsoft, when converting from an RGB to ARGB value

The alpha value is implicitly 255 (fully opaque).

This means by adding FF to a 6 digit (RGB) hex color code it becomes an 8 digit ARGB hex color code. Therefore, a simple method can be created that handles both ARGB and RGB hex's and converts them to the appropriate Color struct.

    public static System.Drawing.Color GetColorFromHexValue(string hex)
    {
        string cleanHex = hex.Replace("0x", "").TrimStart('#');

        if (cleanHex.Length == 6)
        {
            //Affix fully opaque alpha hex value of FF (225)
            cleanHex = "FF" + cleanHex;
        }

        int argb;

        if (Int32.TryParse(cleanHex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out argb))
        {
            return System.Drawing.Color.FromArgb(argb);
        }

        //If method hasn't returned a color yet, then there's a problem
        throw new ArgumentException("Invalid Hex value. Hex must be either an ARGB (8 digits) or RGB (6 digits)");

    }

This was inspired by Hans Kesting's answer.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to wpf

Error: the entity type requires a primary key Reportviewer tool missing in visual studio 2017 RC Pass command parameter to method in ViewModel in WPF? Calling async method on button click Setting DataContext in XAML in WPF How to resolve this System.IO.FileNotFoundException System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll? Binding an Image in WPF MVVM How to bind DataTable to Datagrid Setting cursor at the end of any text of a textbox

Examples related to colors

is it possible to add colors to python output? How do I use hexadecimal color strings in Flutter? How do I change the font color in an html table? How do I print colored output with Python 3? Change bar plot colour in geom_bar with ggplot2 in r How can I color a UIImage in Swift? How to change text color and console color in code::blocks? Android lollipop change navigation bar color How to change status bar color to match app in Lollipop? [Android] How to change color of the back arrow in the new material theme?

Examples related to hex

Transparent ARGB hex value How to convert a hex string to hex number Javascript: Unicode string to hex Converting Hexadecimal String to Decimal Integer Convert string to hex-string in C# Print a variable in hexadecimal in Python Convert ascii char[] to hexadecimal char[] in C Hex transparency in colors printf() formatting for hex Python Hexadecimal