Skip to content

Instantly share code, notes, and snippets.

@jkingry
Created March 30, 2010 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkingry/349210 to your computer and use it in GitHub Desktop.
Save jkingry/349210 to your computer and use it in GitHub Desktop.
// http://stackoverflow.com/questions/2545796/how-to-get-a-majority-color-in-an-image/2546506#2546506
namespace FastImageAverage
{
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
class Program
{
static void Main(string[] args)
{
var watch1 = Stopwatch.StartNew();
Console.WriteLine(UnsafeGetColorAverage(args[0]));
watch1.Stop();
Console.WriteLine(watch1.Elapsed);
var watch2 = Stopwatch.StartNew();
Console.WriteLine(GetColorAverage(args[0]));
watch2.Stop();
Console.WriteLine(watch2.Elapsed);
}
unsafe static Color UnsafeGetColorAverage(string filename)
{
using (var image = (Bitmap)Bitmap.FromFile(filename))
{
if (image.PixelFormat != PixelFormat.Format24bppRgb) throw new NotSupportedException(String.Format("Unsupported pixel format: {0}", image.PixelFormat));
var pixelSize = 3;
var bounds = new Rectangle(0, 0, image.Width, image.Height);
var data = image.LockBits(bounds, ImageLockMode.ReadOnly, image.PixelFormat);
long r = 0;
long g = 0;
long b = 0;
for (int y = 0; y < data.Height; ++y)
{
byte* row = (byte*)data.Scan0 + (y * data.Stride);
for (int x = 0; x < data.Width; ++x)
{
var pos = x * pixelSize;
b += row[pos];
g += row[pos + 1];
r += row[pos + 2];
}
}
r = r / (data.Width * data.Height);
g = g / (data.Width * data.Height);
b = b / (data.Width * data.Height);
image.UnlockBits(data);
return Color.FromArgb((int)r, (int)g, (int)b);
}
}
static Color GetColorAverage(string filename)
{
using (var bmp = new Bitmap(filename))
{
int width = bmp.Width;
int height = bmp.Height;
long red = 0;
long green = 0;
long blue = 0;
long alpha = 0;
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
{
var pixel = bmp.GetPixel(x, y);
red += pixel.R;
green += pixel.G;
blue += pixel.B;
alpha += pixel.A;
}
Func<long, long> avg = c => (c / (width * height));
red = avg(red);
green = avg(green);
blue = avg(blue);
alpha = avg(alpha);
var color = Color.FromArgb((int)alpha, (int)red, (int)green, (int)blue);
return color;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment