从位图中将所有像素的颜色统计出来,然后根据各种颜色出现的次数做个排序。
class PixelColor : IComparable<PixelColor>
{
private System.Drawing.Color _Color;
private int _Count;
public System.Drawing.Color Color
{
get
{
return _Color;
}
set
{
_Color = value;
}
}
public int Count
{
get
{
return _Count;
}
set
{
_Count = value;
}
}
public PixelColor(System.Drawing.Color color)
{
Color = color;
}
static public PixelColor operator ++(PixelColor pixelColor)
{
if (pixelColor != null)
{
pixelColor.Count++;
return pixelColor;
}
else
{
return null;
}
}
public override string ToString()
{
return string.Format("Color={0} Count={1}", Color, Count);
}
#region IComparable<PixelColor> Members
public int CompareTo(PixelColor other)
{
return other.Count.CompareTo(this.Count);
}
#endregion
}
static private List<PixelColor> GetPixelColorFromImageFile(string fileName)
{
System.Drawing.Image image = System.Drawing.Image.FromFile(fileName);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);
Dictionary<System.Drawing.Color, PixelColor> _ColorDict = new Dictionary<System.Drawing.Color, PixelColor>();
for(int x = 0; x < bitmap.Width; x++)
{
for(int y = 0; y < bitmap.Height; y++)
{
System.Drawing.Color color = bitmap.GetPixel(x, y);
if (!_ColorDict.ContainsKey(color))
{
_ColorDict.Add(color, new PixelColor(color));
}
_ColorDict[color]++;
}
}
List<PixelColor> pixelColorList = new List<PixelColor>();
foreach (PixelColor pixelColor in _ColorDict.Values)
{
pixelColorList.Add(pixelColor);
}
pixelColorList.Sort();
return pixelColorList;
}
调用代码
List<PixelColor> pixelColorList = GetPixelColorFromImageFile(@"d:\test\logo.gif");
for(int i = 0 ; i < 10; i++)
{
Console.WriteLine(pixelColorList[i]);
}
执行结果:
Color=Color [A=255, R=255, G=255, B=255] Count=8384
Color=Color [A=255, R=227, G=62, B=6] Count=964
Color=Color [A=255, R=234, G=110, B=68] Count=348
Color=Color [A=255, R=153, G=153, B=153] Count=283
Color=Color [A=255, R=253, G=250, B=250] Count=270
Color=Color [A=255, R=248, G=207, B=193] Count=204
Color=Color [A=255, R=241, G=158, B=130] Count=204
Color=Color [A=255, R=254, G=255, B=249] Count=180
Color=Color [A=255, R=57, G=116, B=196] Count=152
Color=Color [A=255, R=58, G=114, B=189] Count=104