AForge.Imaging.ColorReduction.ErrorDiffusionColorDithering.GetClosestColor C# (CSharp) Method

GetClosestColor() private method

private GetClosestColor ( int red, int green, int blue, byte &colorIndex ) : Color
red int
green int
blue int
colorIndex byte
return Color
        private Color GetClosestColor( int red, int green, int blue, out byte colorIndex )
        {
            Color color = Color.FromArgb( red, green, blue );

            if ( ( useCaching ) && ( cache.ContainsKey( color ) ) )
            {
                colorIndex = cache[color];
            }
            else
            {
                colorIndex = 0;
                int minError = int.MaxValue;

                for ( int i = 0, n = colorTable.Length; i < n; i++ )
                {
                    int dr = red - colorTable[i].R;
                    int dg = green - colorTable[i].G;
                    int db = blue - colorTable[i].B;

                    int error = dr * dr + dg * dg + db * db;

                    if ( error < minError )
                    {
                        minError = error;
                        colorIndex = (byte) i;
                    }
                }

                if ( useCaching )
                {
                    cache.Add( color, colorIndex );
                }
            }

            return colorTable[colorIndex];
        }
    }