Search code examples
c#colorscolor-picker

How to convert color to code and viceversa


I have colors like "FF7B2900" from a program. I need to be able to convert this kind of color code to color and back.

So for example to convert this code to color i'm doing like this:

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

The problem is when i try to convert color to string because i need to pick a color with color picker and get (string) the same type of code together with alpha "FF7B2900" not the simple html code "#7B2900"

Thanks


Solution

  • You can get the exact same hex string back by doing clr.ToArgb().ToString("x").ToUpper(). clr.ToArgb() gets your int back and calling ToString("x") tells it to ouput a hexadecimal string representation of the int.