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.
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.
Here's a much simpler way:
Basically, you use DrawImage to copy the original Bitmap into a 1-pixel Bitmap. The RGB values of that 1 pixel will then represent the averages for the entire original. GetPixel is relatively slow, but only when you use it on a large Bitmap, pixel-by-pixel. Calling it once here is no biggie.
Using LockBits is indeed fast, but some Windows users have security policies that prevent the execution of "unsafe" code. I mention this because this fact just bit me on the behind recently.
Update: with InterpolationMode set to HighQualityBicubic, this method takes about twice as long as averaging with LockBits; with HighQualityBilinear, it takes only slightly longer than LockBits. So unless your users have a security policy that prohibits
unsafe
code, definitely don't use my method.Update 2: with the passage of time, I now realize why this approach doesn't work at all. Even the highest-quality interpolation algorithms incorporate only a few neighboring pixels, so there's a limit to how much an image can be squashed down without losing information. And squashing a image down to one pixel is well beyond this limit, no matter what algorithm you use.
The only way to do this would be to shrink the image in steps (maybe shrinking it by half each time) until you get it down to the size of one pixel. I can't express in mere words what an utter waste of time writing something like this would be, so I'm glad I stopped myself when I thought of it. :)
Please, nobody vote for this answer any more - it might be my stupidest idea ever.
The fastest way is by using unsafe code:
Beware: I didn't test this code... (I may have cut some corners)
This code also asssumes a 32 bit image. For 24-bit images. Change the x*4 to x*3
This kind of thing will work but it may not be fast enough to be that useful.