How to calculate the average rgb color values of a bitmap

后端 未结 3 1610
猫巷女王i
猫巷女王i 2020-11-29 01:47

In my C# (3.5) application I need to get the average color values for the red, green and blue channels of a bitmap. Preferably without using an external library. Can this be

3条回答
  •  情书的邮戳
    2020-11-29 02:34

    This kind of thing will work but it may not be fast enough to be that useful.

    public static Color GetDominantColor(Bitmap bmp)
    {
    
           //Used for tally
           int r = 0;
           int g = 0;
           int b = 0;
    
         int total = 0;
    
         for (int x = 0; x < bmp.Width; x++)
         {
              for (int y = 0; y < bmp.Height; y++)
              {
                   Color clr = bmp.GetPixel(x, y);
    
                   r += clr.R;
                   g += clr.G;
                   b += clr.B;
    
                   total++;
              }
         }
    
         //Calculate average
         r /= total;
         g /= total;
         b /= total;
    
         return Color.FromArgb(r, g, b);
    }
    

提交回复
热议问题