Duality.ExtMethodsBitmap.GetAverageColor C# (CSharp) Method

GetAverageColor() public static method

Determines the average color of a Bitmap.
public static GetAverageColor ( this bm, bool weightTransparent = true ) : ColorRgba
bm this
weightTransparent bool If true, the alpha value weights a pixels color value.
return ColorRgba
        public static ColorRgba GetAverageColor(this Bitmap bm, bool weightTransparent = true)
        {
            float[] sum = new float[4];
            int count = 0;
            ColorRgba[] pixelData = bm.GetPixelDataRgba();

            if (weightTransparent)
            {
                for (int i = 0; i < pixelData.Length; i++)
                {
                    sum[0] += pixelData[i].R * ((float)pixelData[i].A / 255.0f);
                    sum[1] += pixelData[i].G * ((float)pixelData[i].A / 255.0f);
                    sum[2] += pixelData[i].B * ((float)pixelData[i].A / 255.0f);
                    sum[3] += (float)pixelData[i].A / 255.0f;
                    ++count;
                }
                if (sum[3] <= 0.001f) return ColorRgba.TransparentBlack;

                return new ColorRgba(
                    (byte)MathF.Clamp((int)(sum[0] / sum[3]), 0, 255),
                    (byte)MathF.Clamp((int)(sum[1] / sum[3]), 0, 255),
                    (byte)MathF.Clamp((int)(sum[2] / sum[3]), 0, 255),
                    (byte)MathF.Clamp((int)(sum[3] / (float)count), 0, 255));
            }
            else
            {
                for (int i = 0; i < pixelData.Length; i++)
                {
                    sum[0] += pixelData[i].R;
                    sum[1] += pixelData[i].G;
                    sum[2] += pixelData[i].B;
                    sum[3] += pixelData[i].A;
                    ++count;
                }
                if (count == 0) return ColorRgba.TransparentBlack;

                return new ColorRgba(
                    (byte)MathF.Clamp((int)(sum[0] / (float)count), 0, 255),
                    (byte)MathF.Clamp((int)(sum[1] / (float)count), 0, 255),
                    (byte)MathF.Clamp((int)(sum[2] / (float)count), 0, 255),
                    (byte)MathF.Clamp((int)(sum[3] / (float)count), 0, 255));
            }
        }