Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Round Color to Colors in a list

I have a list of colors in HEX format:

String[] validcolors = new String[]
{
    "0055A5",
    "101010",
    "E4D200",
    "FFFFFF",
    "006563",
    "A97B3E",
    "B80000",
    "6E3391",
    "D191C3",
    "D68200",
    "60823C",
    "AA8D73",
    "73A1B8",
    "6E6D6E",
    "00582C",
    "604421"
};    

And a color object:

Color c = ...

I want to find the color that is closest to c in validcolors. Can somebody help me out? My initial idea was 'closest by RGB value', but whatever works is fine.

like image 883
Entity Avatar asked Feb 25 '23 15:02

Entity


2 Answers

I would think of transforming the hex to .NET color then calculating somr sort of distance ((x2-x1)²+(y2-y1)²) and taking the closest using this distance:

string closestColor = "";
double diff = 200000; // > 255²x3

foreach(string colorHex in validColors)
{
    Color color = System.Drawing.ColorTranslator.FromHtml("#"+colorHex);
    if(diff > (diff = (c.R - color.R)²+(c.G - color.G)²+(c.B - color.B)²))
        closestColor = colorHex;
}

return closestColor;
like image 74
manji Avatar answered Mar 11 '23 05:03

manji


The distance between two colors depends on the color model you are using. See this article in the Wikipedia so until we know what model you prefer we can't help.

like image 41
Emond Avatar answered Mar 11 '23 05:03

Emond