4

I allow users of my app to select custom colors and want a way to display a friendly name for each color instead of displaying a text representation of the hex code.

How do I find the closest System.Drawing.Color for a given hex code?

Greg
  • 8,574
  • 21
  • 67
  • 109
  • I was looking for a way do this yesterday! It would be nice if this were hosted on a website somewhere. Then we could just enter the number and get out the color. – Michael Oct 11 '13 at 16:55

1 Answers1

5

Hope this helps somebody...

Public Function GetClosestColor(hex_code As String) As Color
    Dim c As Color = ColorTranslator.FromHtml(hex_code)
    Dim closest_distance As Double = Double.MaxValue
    Dim closest As Color = Color.White

    For Each kc In [Enum].GetValues(GetType(KnownColor)).Cast(Of KnownColor).Select(Function(x) Color.FromKnownColor(x))
        'Calculate Euclidean Distance
        Dim r_dist_sqrd As Double = Math.Pow(CDbl(c.R) - CDbl(kc.R), 2)
        Dim g_dist_sqrd As Double = Math.Pow(CDbl(c.G) - CDbl(kc.G), 2)
        Dim b_dist_sqrd As Double = Math.Pow(CDbl(c.B) - CDbl(kc.B), 2)
        Dim d As Double = Math.Sqrt(r_dist_sqrd + g_dist_sqrd + b_dist_sqrd)

        If d < closest_distance Then
            closest_distance = d
            closest = kc
        End If
    Next

    Return closest
End Function
Greg
  • 8,574
  • 21
  • 67
  • 109
  • 1
    There's no real reason to perform a (relatively expensive) square-root since the closest by distance squared is the same as the closest by distance. Furthermore, whilst it probably won't affect your results much, this method may not produce the perceptually "closest" color in some cases. You may want to have a look at this answer for other approaches: http://stackoverflow.com/questions/4057475/rounding-colour-values-to-the-nearest-of-a-small-set-of-colours – Iridium Oct 11 '13 at 17:30