How to find base color by hex color value in C#

721 Views Asked by At

Given a Hex color code how to categorize the color as whether it belongs to the Red/Green/Yellow/Pink/Orange/Blue in C#?

2

There are 2 best solutions below

0
On

I guess you could get a RGB Color code from your hex code and maybe get the base color red, blue or green by comparing each R(ed)G(reen)B(lue) value and picking the highest number. So e.g. you have RGB(254, 120, 5). This Color code probably matches the color red the most.

0
On

Maybe you can get what you want from this code. It calculates the distance of the color you input in hex to a given color from a pool, and then reurns the least distance color.

I programmed this in a course, you could add more rgb colors and store them better than just creating this list every time... but you should get what i mean

using System;
using System.Collections.Generic;
using System.Collections;
using System.Globalization;
                
public class Program
{
    public static void Main()
    {
        string hex = "ffffff";
    
        int r,g,b = 0;

        r = int.Parse(hex.Substring(0, 2), NumberStyles.AllowHexSpecifier);
        g = int.Parse(hex.Substring(2, 2), NumberStyles.AllowHexSpecifier);
        b = int.Parse(hex.Substring(4, 2), NumberStyles.AllowHexSpecifier);
    
        List<Color> Colors = new List<Color>{};

        Colors.Add(new Color("red", 255, 0, 0));
        Colors.Add(new Color("yellow", 255, 255, 0));
        Colors.Add(new Color("green", 0, 255, 0));
        Colors.Add(new Color("cyan", 0, 255, 255));
        Colors.Add(new Color("blue", 0, 0, 255));
        Colors.Add(new Color("magenta", 255, 0, 255));
        Colors.Add(new Color("white", 255, 255, 255));
        Colors.Add(new Color("grey", 127, 127, 127));
        Colors.Add(new Color("black", 0, 0, 0));
    
        int tmp_distance = 255*3;
        Color result = new Color();
    
        foreach(Color color in Colors)
        {
            int r_distance = Math.Abs(color.RGBValue[0] - r);
            int g_distance = Math.Abs(color.RGBValue[1] - g);                 
            int b_distance = Math.Abs(color.RGBValue[2] - b);   
        
            int total_distance = r_distance + g_distance + b_distance;
                          
            if(total_distance < tmp_distance)
            {
                result = color;
                tmp_distance = total_distance;
            }
            
        }
                          
        Console.WriteLine(result.Name);
                          
    }
                          
    
}

public class Color
{
    public Color(string name, int r, int g, int b)
    {
        Name = name;
    
        RGBValue = new int[3];
    
        RGBValue[0] = r;
        RGBValue[1] = g;
        RGBValue[2] = b;
    }

    public Color(){}

    public string Name {get; set;}
    public int[] RGBValue {get; set;}
}