How to find the average color of an image.
- by Edward Boyle
Years ago I was the lead developer of a large Scrapbook Web Site. One of the things I implemented was to allow shoppers to find Scrapbook papers and embellishments of like colors (“more like this color”). Below is the base algorithm I wrote to extract the color from an image. It worked out pretty well. I took the returned values and stored them in an associated table for the products. Yet another algorithm was used to SELECT near matches.
This algorithm has turned out to be very handy for me. I have used it for borders and subtle outlined text overlays. I am sure you will find more creative uses for it. Enjoy…
private Color GetColor(Bitmap bmp)
{
int r = 0;
int g = 0;
int b = 0;
Color mColor = System.Drawing.Color.White;
for (int i = 1; i < bmp.Width; i++)
{
for (int x = 1; x < bmp.Height; x++)
{
mColor = bmp.GetPixel(i, x);
r += mColor.R;
g += mColor.G;
b += mColor.B;
}
}
r = (r / (bmp.Height * bmp.Width));
g = (g / (bmp.Height * bmp.Width));
b = (b / (bmp.Height * bmp.Width));
return System.Drawing.Color.FromArgb(r, g, b);
}
You could also get the RGB values by passing in the RGB by ref
private Color GetColor(ref int r, ref int g, ref int b, Bitmap bmp) but that is a bit much as you can simply get it from the return value: mReturnedColor.R; mReturnedColor.G; mReturnedColor.B;