698

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?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
viky
  • 17,275
  • 13
  • 71
  • 90

20 Answers20

829

I'm assuming that's an ARGB code... Are you referring to System.Drawing.Color or System.Windows.Media.Color? The latter is used in WPF for example. I haven't seen anyone mention it yet, so just in case you were looking for it:

using System.Windows.Media;

Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");
Thorarin
  • 47,289
  • 11
  • 75
  • 111
  • @Thorarin any help on how to get alpha value as I need to convert this value to be compatible with css rgba for web design. – KKS Apr 17 '14 at 08:14
  • 4
    @Yoda The first two digits (FF) are the alpha value. It's probably easier to use the `Color.FromArgb` method in this case though. If you use floating point alpha, you'd have to multiply by 255. – Thorarin Apr 18 '14 at 18:20
  • 2
    in case you have the RGB values -> Color.FromArgb(255,192,0) – Iman Nov 12 '14 at 08:30
  • 74
    string hex = "#FFFFFF"; Color _color = System.Drawing.ColorTranslator.FromHtml(hex); – Harshal Doshi Jain Nov 29 '14 at 07:41
  • 2
    why not use color.FromArgb() instead? – Nimitz E. Jul 10 '15 at 20:44
  • Why not using FromArgb because it is simpler to copy past from Microsoft page.... https://msdn.microsoft.com/en-us/library/system.windows.media.colors(v=vs.110).aspx – Thomas J Younsi May 14 '18 at 03:21
  • Works fine, though, you need to create an instance of ColorConverter before using its ConvertFromString method – ZooZ Feb 03 '22 at 05:47
616

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") ;
T.Todua
  • 53,146
  • 19
  • 236
  • 237
Oded
  • 489,969
  • 99
  • 883
  • 1,009
141

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)

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
  • Great solution for those using Visual C# Express since it only requires `System.Globalization`. – marshall.ward Mar 11 '12 at 01:19
  • +1: very nice to use. Used it in VB.NET: clr = Color.FromArgb(Int32.Parse("FFFFFF00", Globalization.NumberStyles.HexNumber)) – Andrea Antonangeli Oct 07 '12 at 17:20
  • 3
    Color.FromArgb requires a, r, g, and b parameters, not an integer. – citizen conn Nov 30 '12 at 22:41
  • 7
    This is also useful if you are using the Compact Framework in which ColorTranslator is not available – TechyGypo Apr 23 '13 at 12:25
  • 1
    On Windows Phone at least, Color.FromArgb takes 4 byte arguments, not an int. – Leon Storey Oct 26 '13 at 01:20
  • 7
    @user1763532 - After `colorcode = colorcode.Replace("#", "")` simply use `int a = byte.parse(colorcode.Substring(0,2), NumberStyles.HexNumber);` and so on for r, g, and b. Don't forget to replace the first parameter of Substring - the index - with 2 for r, 4 for g and 6 for b. – M. Mimpen Dec 24 '13 at 11:29
  • 4
    @HansKesting, `FromArgb` takes 1 parameter in `System.Drawing.Color` and 4 paramteres in `System.Windows.Media.Color` – torvin Oct 08 '15 at 22:16
  • 2
    Note this works for a 4 byte (eg. #FFFFFFFF) HTML colour (inc alpha). If you try with a 3 byte (#FFFFFF) alpha will be 0 and your colour transparent. You can easilly insert alpha if the color code is less than 8/9 chars. Great for Compact Framework. – apc May 29 '18 at 16:22
  • This also won't work for the short hand 3 or 4 digit color definitions. – MrPaulch Jun 10 '21 at 16:33
42

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
demp
  • 12,665
  • 2
  • 23
  • 17
41

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();
Jink
  • 451
  • 4
  • 6
  • 7
    Maybe a stupid question, and a little late, but why do you use -16777216 for the alpha value? – GeekPeek Mar 26 '12 at 08:49
  • 5
    Small variation consistently using hex: return Color.FromArgb((byte)((argb & 0xff000000) >> 0x18), (byte)((argb & 0xff0000) >> 0x10), (byte)((argb & 0xff00) >> 0x08), (byte)(argb & 0xff)); – too Dec 12 '13 at 15:46
  • 1
    This code is faulty. I couldn't figure out why nothing was showing up and it turned out to be because this code doesn't convert hex to ``Color`` properly. I used the code from @too and that fixed it. – SameOldNick May 31 '14 at 07:00
  • Here there is a previous version this answer in so: [http://stackoverflow.com/a/784852/2721611](http://stackoverflow.com/a/784852/2721611) – Mojtaba Rezaeian Oct 24 '15 at 18:21
  • 1
    You can just do `& 0xFF` on the final downshifted value each time, instead of needing all those different values to `&` it with. – Nyerguds Nov 25 '16 at 00:40
  • @Nyerguds Agreed. And then the shift values will be powers of 2. – mbomb007 Jan 04 '17 at 21:55
  • 1
    Doesn't `Color.FromArgb` have an overload that simply accepts an `Int32` though? I mean, `System.Drawing.Color` sure does. – Nyerguds Mar 01 '18 at 23:35
17

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));
ConfusedDeer
  • 3,335
  • 8
  • 44
  • 72
14
    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));
    }
Baddack
  • 1,947
  • 1
  • 24
  • 33
  • 2
    In UWP Color.FromArgb() requires 4 byte arguments. So it will look like: return Color.FromArgb(255, byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber), byte.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber), byte.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber)); – Kibernetik Jul 16 '16 at 09:10
12

You could use the following code:

Color color = System.Drawing.ColorTranslator.FromHtml("#FFDFD991");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pengzhi
  • 121
  • 1
  • 3
6

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));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Youngjae
  • 24,352
  • 18
  • 113
  • 198
5

in asp.net:

color_black = (Color)new ColorConverter().ConvertFromString("#FF76B3");
Khalil Youssefi
  • 385
  • 6
  • 10
4

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.

Justin
  • 582
  • 9
  • 24
1

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

your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

You can use the ColorConverter.ConvertFromString(string) method which converts your string (hexadecimal) to the color.

Example: (This works with ARGB, like "#FF1E1E1E".

Control.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#1E1E1E"));
TERIHAX
  • 237
  • 2
  • 14
1

For any Xamarin developers out there, you will need to

  1. Specify the color type in order to prevent Cast exception from assuming you are talking about Xamarin.Forms.Color instead
  2. Create an object of type ColorConverter
var conv = new System.Drawing.ColorConverter();
var color = (System.Drawing.Color)conv.ConvertFromString("#FF1D65AE");
Saamer
  • 4,687
  • 1
  • 13
  • 55
0

WPF:

using System.Windows.Media;

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

//color to hex
string hexcolor = color.ToString();
Max Truxa
  • 3,308
  • 25
  • 38
DevXP
  • 17
  • 1
0

Use

System.Drawing.Color.FromArgb(myHashCode);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
herzmeister
  • 11,101
  • 2
  • 41
  • 51
0

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.

Cevdet
  • 69
  • 9
0

There are many answers here already.

In short I support those that propose to use System.Drawing.ColorTranslator.

I get that some people want to avoid System.Windows.Media so there is the other solution, and since you want to have a System.Drawing.Color you should have a reference to System.Drawing already in your project.

So in short: Use the Framework if you can.

A more complete native solution

So, if for some reason you want to avoid System.Drawing.ColorTranslator and create your own implementation, you should at least make it respect the specifications

So this is a solution that does #RGB and #RGBA shorthand - and extended color definition

    public static Color ParseHtmlColor(string htmlColor) => Color.FromArgb(HtmlColorToArgb(htmlColor));

    public static int HtmlColorToArgb(string htmlColor, bool requireHexSpecified = false, int defaultAlpha = 0xFF)
    {

        if (string.IsNullOrEmpty(htmlColor))
        {
            throw new ArgumentNullException(nameof(htmlColor));
        }

        if (!htmlColor.StartsWith("#") && requireHexSpecified)
        {
            throw new ArgumentException($"Provided parameter '{htmlColor}' is not valid");
        }

        htmlColor = htmlColor.TrimStart('#');
        

        // int[] symbols 
        var symbolCount = htmlColor.Length;
        var value = int.Parse(htmlColor, System.Globalization.NumberStyles.HexNumber);
        switch (symbolCount)
        {
            case 3: // RGB short hand
            {
                return defaultAlpha << 24
                    | (value & 0xF)
                    | (value & 0xF) << 4
                    | (value & 0xF0) << 4
                    | (value & 0xF0) << 8
                    | (value & 0xF00) << 8
                    | (value & 0xF00) << 12
                    ;
            }
            case 4: // RGBA short hand
            {
                // Inline alpha swap
                return   (value & 0xF) << 24
                       | (value & 0xF) << 28
                       | (value & 0xF0) >> 4
                       | (value & 0xF0) 
                       | (value & 0xF00) 
                       | (value & 0xF00) << 4
                       | (value & 0xF000) << 4
                       | (value & 0xF000) << 8
                       ;
            }
            case 6: // RGB complete definition
            {
                return defaultAlpha << 24 | value;   
            }
            case 8: // RGBA complete definition
            {
                // Alpha swap
                return (value & 0xFF) << 24 | (value >> 8);
            }
            default:
                throw new FormatException("Invalid HTML Color");
        }
    }

If you for some reason don't want to use System.Globalization I'm sure you'll find a code snipped for parsing hex symbols.

Tests

    public static void TestColors()
    {
        foreach (var testCase in TestCases) TestColor(testCase);
    }

    static string[] TestCases = new string[] { 
        "111",
        "FFF", 
        "17A",
        "F52",
        "444F",
        "2348",
        "4320",
        "121212",
        "808080",
        "FFFFFF",
        "A0E0C0",
        "0A070B",
        "FFFFFFFF",
        "808080FF",
        "40807710"
    };

    public static void TestColor(string htmlColor)
    {
        Console.Write($" {htmlColor} -> ");
        var color = ParseHtmlColor(htmlColor);
        Console.WriteLine("0x" + color.ToArgb().ToString("X"));
    }

P.S.: Feel free to remove the paramters, they only intend to show how you could tweak the function to handle format errors and defaults.

P.P.S.: The error messages are not very descriptive at the moment

MrPaulch
  • 1,423
  • 17
  • 21
0
  • XNA / Monogame (Microsoft.Xna.Framework.Color).
  • Works for 6 or 8 (with alpha) character hexadecimal strings
  • Probably better alternatives (bit masking/shifting) out there.
    using Microsoft.Xna.Framework;
    using System.Globalization;
    
    public static class ColorBuilder
    {
        public static Color FromHex(string color)
        {
            var hex = color.Replace("#", string.Empty);
            var h = NumberStyles.HexNumber;

            var r = int.Parse(hex.Substring(0, 2), h);
            var g = int.Parse(hex.Substring(2, 2), h);
            var b = int.Parse(hex.Substring(4, 2), h);
            var a = 255;

            if (hex.Length == 8)
            {
                a = int.Parse(hex.Substring(6, 2), h);
            }
 
            return new Color(r, g, b, a);
        }
    }
    
    //create a blue color
    var color = ColorBuilder.FromHex("#2733C5"); //or ColorBuilder.FromHex("2733C5");
    
    //create a blue color with 50% alpha
    var colorTrans = ColorBuilder.FromHex("#2733C580");

Gerhard Schreurs
  • 663
  • 1
  • 8
  • 19
-2

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Wim
  • 11,998
  • 1
  • 34
  • 57
  • 1
    @Wim Thanks for helping the OP clarify the question. I would say this answer is no longer needed, and recommend deleting it. – jpaugh Jul 03 '18 at 15:26