我是菜鸟,写点东西,怕自己忘了!!
好久没有写东西,今天看CSDN的时候,看到一个朋友在问统计某颜色所占总面积的比例的问题:
1。获取一个图像的Bitmap类型,有N种方法得到,下面说两种
(1)从this.pictureBox1.Image得到
(2)(Bitmap)Bitmap.FromFile(openFileDialog.FileName, false);
2。主程序
unsafe
{
Bitmap bitmap = (Bitmap)this.pictureBox1.Image.Clone();
Color color = bitmap.GetPixel(e.X, e.Y );
label2.BackColor = color;
Rectangle rect = new Rectangle( 0, 0, bitmap.Width, bitmap.Height );
BitmapData bitmapData = bitmap.LockBits( rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb );
int sum = 0;
int* colorData = (int*) bitmapData.Scan0.ToPointer();
for( int i = 0; i < bitmap.Width * bitmap.Height; i ++ )
{
if(colorData[ i ] == Color.FromArgb( color.R, color.G, color.B ).ToArgb())
{
sum++;
}
}
bitmap.UnlockBits( bitmapData );
bitmapData = null;
//结果
label1.Text = sum.ToString();
}
{
Bitmap bitmap = (Bitmap)this.pictureBox1.Image.Clone();
Color color = bitmap.GetPixel(e.X, e.Y );
label2.BackColor = color;
Rectangle rect = new Rectangle( 0, 0, bitmap.Width, bitmap.Height );
BitmapData bitmapData = bitmap.LockBits( rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb );
int sum = 0;
int* colorData = (int*) bitmapData.Scan0.ToPointer();
for( int i = 0; i < bitmap.Width * bitmap.Height; i ++ )
{
if(colorData[ i ] == Color.FromArgb( color.R, color.G, color.B ).ToArgb())
{
sum++;
}
}
bitmap.UnlockBits( bitmapData );
bitmapData = null;
//结果
label1.Text = sum.ToString();
}