通过传统的内存法,在计算灰度的for改为Parallel.For进行并发,比之前提升了0.5-1倍左右
源码如下:
public static Bitmap Gray_BitmapData(Bitmap bitmap)
{
int width = bitmap.Width;
int height = bitmap.Height;
// 在内存中以读写模式锁定Bitmap
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
// 获取第一个像素的地址
IntPtr ptr = bitmapData.Scan0;
//图片像素点数组的长度,由于一个像素点占了3个字节,所以要乘上3
int size = width * height * 3;
//缓冲区数组
byte[] srcArray = new byte[size];
//把像素值复制到缓冲区
Marshal.Copy(ptr, srcArray, 0, size);
Parallel.For(0, width * height, (i, loopState) =>
{
byte color1 = (byte)((srcArray[i * 3] + srcArray[i * 3 + 1] + srcArray[i * 3 + 2]) / 3);
// 计算灰度值并写入原位
Marshal.WriteByte(ptr, i * 3, color1);
Marshal.WriteByte(ptr, i * 3 + 1, color1);
Marshal.WriteByte(ptr, i * 3 + 2, color1);
});
// 从内存中解锁
bitmap.UnlockBits(bitmapData);
return bitmap;
}