如何计算位图的平均RGB颜色值

问题描述:

在我的C#(3.5)申请我需要得到的平均颜色值的位图的红色,绿色和蓝色通道。 preferably不使用外部库。可以这样做?如果是这样,怎么样?先谢谢了。

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 done? If so, how? Thanks in advance.

试图让事情更加precise:位图中​​的每个像素都具有一定的RGB颜色值。我想获得的平均RGB值图像中的所有像素。

Trying to make things a little more precise: Each pixel in the bitmap has a certain RGB color value. I'd like to get the average RGB values for all pixels in the image.

的最快方法是使用不安全的code:

The fastest way is by using unsafe code:

BitmapData srcData = bm.LockBits(
            new Rectangle(0, 0, bm.Width, bm.Height), 
            ImageLockMode.ReadOnly, 
            PixelFormat.Format32bppArgb);

int stride = srcData.Stride;

IntPtr Scan0 = srcData.Scan0;

long[] totals = new long[] {0,0,0};

int width = bm.Width;
int height = bm.Height;

unsafe
{
  byte* p = (byte*) (void*) Scan0;

  for (int y = 0; y < height; y++)
  {
    for (int x = 0; x < width; x++)
    {
      for (int color = 0; color < 3; color++)
      {
        int idx = (y*stride) + x*4 + color;

        totals[color] += p[idx];
      }
    }
  }
}

int avgB = totals[0] / (width*height);
int avgG = totals[1] / (width*height);
int avgR = totals[2] / (width*height);

请注意:我没有测试此code ...(我可能会削减一些角落)

Beware: I didn't test this code... (I may have cut some corners)

这code也asssumes一个32位的图像。对于24位图像。更改的 X * 4 X * 3

This code also asssumes a 32 bit image. For 24-bit images. Change the x*4 to x*3