三种图象处理的效率比较,用指针法最快
//象素法,大概400毫秒一张
private void pixel_Click(object sender, EventArgs e)
{
if(curBitmap != null)
{
myTimer.ClearTimer();
myTimer.Start();
Color curColor;
int ret;
for (int i = 0; i < curBitmap.Width; i++)
{
for (int j = 0; j < curBitmap.Height ; j++)
{
curColor = curBitmap.GetPixel(i,j);
ret = (int)(curColor.R * 0.299 + curColor.G * 0.587 + curColor.B * 0.114);
curBitmap.SetPixel(i, j, Color.FromArgb(ret, ret, ret));
}
}
myTimer.Stop();
timeBox.Text = myTimer.Duration.ToString("####.##") + " 毫秒";
Invalidate();
}
}
//内存法,大概2.5毫秒一张.
private void memory_Click(object sender, EventArgs e)
{
if (curBitmap != null)
{
myTimer.ClearTimer();
myTimer.Start();
Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
System.Drawing.Imaging.BitmapData bmpData = curBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmap.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = curBitmap.Width * curBitmap.Height * 3;
byte[] rgbValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
double colorTemp = 0;
for (int i = 0; i < rgbValues.Length; i += 3)
{
colorTemp = rgbValues[i + 2] * 0.299 + rgbValues[i + 1] * 0.587 + rgbValues[i] * 0.114;
rgbValues[i] = rgbValues[i + 1] = rgbValues[i + 2] = (byte)colorTemp;
}
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
curBitmap.UnlockBits(bmpData);
myTimer.Stop();
timeBox.Text = myTimer.Duration.ToString("####.##") + " 毫秒";
Invalidate();
}
}
//这种方法是最快的,大概1.7毫秒一张.
private void pointer_Click(object sender, EventArgs e)
{
if (curBitmap != null)
{
myTimer.ClearTimer();
myTimer.Start();
Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
System.Drawing.Imaging.BitmapData bmpData = curBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmap.PixelFormat);
byte temp = 0;
unsafe
{
byte* ptr = (byte*)(bmpData.Scan0);
for (int i = 0; i < bmpData.Height; i++)
{
for (int j = 0; j < bmpData.Width; j++)
{
temp = (byte)(0.299 * ptr[2] + 0.587 * ptr[1] + 0.114 * ptr[0]);
ptr[0] = ptr[1] = ptr[2] = temp;
ptr += 3;
}
ptr += bmpData.Stride - bmpData.Width * 3;
}
}
curBitmap.UnlockBits(bmpData);
myTimer.Stop();
timeBox.Text = myTimer.Duration.ToString("####.##") + " 毫秒";
Invalidate();
}
}