简体   繁体   中英

How to get the color's name from input type=“color” with C#

I have this <input type="color" id="favcolor"> . now I want to store the color's name. I mean: red, blue, black,etc.

the value I'm getting from the textbox is: #ffffff (favcolor.text.tostring();. related to the picked color). how can I cget the color's name?

I want to store: red, blue, black, white .. just like that! no html code, no rgb color! I want the color's name using: C#

by the way, I have already tried:

Color mycolor = Color.FromName("red"); then what you get is .. #FF0000 i want the opposite

Consider this: Color. FromName

EDIT:

System.Array colorsArray = Enum.GetValues(typeof(KnownColor));
KnownColor[] allColors = new KnownColor[colorsArray.Length];
Array.Copy(colorsArray, allColors, colorsArray.Length);
var colorValueToColorMap = allColors.ToDictionary(x => Color.FromName(x.ToString()).ToString().ToLower(), Color.FromName(x.ToString()));

var colorValue = "#FF0000";
var argbColorValue = "#" + "FF" +  colorValue.Substring(1);
var color = colorValueToColorMap[argbColorValue.ToLower()];

You can use following code, Note that only for the known colors you will get the expected color name (Red,Aqua,Green).

Color color = System.Drawing.ColorTranslator.FromHtml("#FF98FB98");
string colorName = color.Name;

Outputs

FF32CD32 => LimeGreen

FF00FFFF => Aqua

You'll need to iterate over the known colors converting them to hex code and compare for a match.

var colorInfo= Enum.GetValues(typeof(KnownColor))
                .Cast<KnownColor>()
                .Select(x => new { Name = x.ToString(), Color = FromKnownColor(x) })
                .FirstOrDefault(x => x.Color.ToArgb() == submittedColorArgbCode);

           return (colorInfo != null) ? colorInfo.Name:"Unknown";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM