Download ColorDistanceDemonstration.zip, last updated 06/01/2017 (17.99 KB)

Download
  • md5: ed252649e2f394f1c4407629e53fbca8
  • sha1: b112562ad8a80779f6359b7902e84ac8f9c75f02
  • sha256: a791f5e43926bedbf9ba25606cf7d325046c708ca7f86e2f918d31c34b9ef613
using System.Drawing;

/* Finding nearest colors using Euclidean distance
 * http://www.cyotek.com/blog/finding-nearest-colors-using-euclidean-distance
 *
 * Copyright © 2017 Cyotek Ltd.
 */

namespace Cyotek.ColorDistanceDemonstration
{
  internal static class ColorHelpers
  {
    #region Static Methods

    public static int FindNearestColor(Color[] map, Color current)
    {
      int shortestDistance;
      int index;

      index = -1;
      shortestDistance = int.MaxValue;

      for (int i = 0; i < map.Length; i++)
      {
        Color match;
        int distance;

        match = map[i];
        distance = GetDistance(current, match);

        if (distance < shortestDistance)
        {
          index = i;
          shortestDistance = distance;
        }
      }

      return index;
    }

    public static int GetDistance(Color current, Color match)
    {
      int redDifference;
      int greenDifference;
      int blueDifference;
      int alphaDifference;

      alphaDifference = current.A - match.A;
      redDifference = current.R - match.R;
      greenDifference = current.G - match.G;
      blueDifference = current.B - match.B;

      return alphaDifference * alphaDifference + redDifference * redDifference + greenDifference * greenDifference + blueDifference * blueDifference;
    }

    #endregion
  }
}

Donate

Donate