user571874
user571874

Reputation: 589

System.Drawing.Color convert FromArgb issue

I'm saving my color in db in int value.

int icolor = System.Drawing.Color.Red.ToArgb();
//result: -65536

When convert int to Color than lost property Color.Name. Must return "Red" but property return "ff000000". What I doing wrang?

I need get this one - property Red but not hex value

Upvotes: 1

Views: 5699

Answers (4)

Shai
Shai

Reputation: 25619

You're doing nothing wrong.

ff in hex equals 255 which is the decimal value for the Red color, which is being returned by System.Drawing.Color.Red.ToArgb();

If you'd like to get the name of the color, use System.Drawing.Color.Red.Name

string sRedColorName = System.Drawing.Color.Red.Name;

Upvotes: 4

hcb
hcb

Reputation: 8357

You mixed up known colors and just colors. When you convert a known color to int, and convert it back to color you lose the name. You have to do this:

 int icolor = System.Drawing.Color.Red.ToArgb();

 Color knownColor = System.Drawing.Color.FromArgb(icolor).ToKnownColor();

Upvotes: 0

Vano Maisuradze
Vano Maisuradze

Reputation: 5899

Try this

System.Drawing.ColorTranslator.FromHtml("#" + "Hex value").Name

Upvotes: 7

Cody Gray
Cody Gray

Reputation: 244742

When convert int to Color than lost property Color.Name.

Yes, that's correct. This is how the Color.Name property works. According to the documentation:

This method returns either the user-defined name of the color, if the color was created from a name, or the name of the known color. For custom colors, the RGB value is returned.

So since you're creating a Color object from the integer (RGB) value—not its name—the Color structure doesn't recognize it as a named color.

This information is not dynamically determined at runtime by iterating through a map containing all of the known colors and their RGB values, but rather stored in private sentinel fields at the time that the Color object is created. You are losing that information in the process of serializing the color information to your database as an integer.

Upvotes: 2

Related Questions