views:

93

answers:

3

I need to serialize a color used in a WPF application to a database. I'd like to use the sRGB values, because they're more familiar to those of us that have spent the last few years doing web development.

How can a get an ARGB string (like #FFFFFFFF) from a System.Windows.Media.Color object?

UPDATE: I was misled by the documentation on MSDN. As @Kris noted below, the documentation for the ToString() method is incorrect. Although it says that ToString() "creates a string representation of the color using the ScRGB channels", it will actually return a string in ARGB hex format if the color was created using the FromARGB() method. It's an undocumented feature, I suppose.

See http://msdn.microsoft.com/en-us/library/ms606572.aspx

A: 

You can get the A, R, G and B values from a Color instance as bytes, so you just need to convert the bytes to hex and concatenate the hex values as strings.

http://stackoverflow.com/questions/623104/c-byte-to-hex-string

AndrewS
A: 

you can get the HTML color string (and back) like this

System.Drawing.Color c = System.Drawing.ColorTranslator.FromHtml("#F5F7F8");
String strHtmlColor = System.Drawing.ColorTranslator.ToHtml(c);

here is the MSDN documentation. I should probably not that these are GDI colors, and not WPF, so might not be much help.

Muad'Dib
That is for System.Drawing.Color (GDI+), not System.Windows.Media.Color (WPF).
AndrewS
yes, as I noted.
Muad'Dib
+2  A: 

If you create your colors using either Color.FromRgb or Color.FromArgb instead of FromScRgb you should get a hex string result from ToString.

If you want to do it manually

string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", c.A, c.R, c.G, c.B);

You can use int.Parse(,NumberStyles.HexNumber) to go the other way.

Note sRGB and scRGB refer to different color spaces, make sure your using the one you want.

Kris
You mean that if I created the Color object using FromArgb, ToString will return the ARGB hex string instead of the ScRgb value? That contradicts what it says in the MSDN documentation: http://msdn.microsoft.com/en-us/library/ms606572.aspx.
dthrasher
I hadn't noticed that in the documentation but it does generate a hex format when using those methods. Looking in reflector a flag is set which is used in the ToString implementation.
Kris
Yup. ToString() gives me the format I want. Looks like the MSDN documentation is incomplete.
dthrasher