这是绝对最快吗?我可以可能将Bitmap
复制到中的
?Byte[]
>C#
如果有更快的方法我很想知道!
const int WIDTH = /* width */;
const int HEIGHT = /* height */;
Bitmap bitmap = new Bitmap(WIDTH, HEIGHT, PixelFormat.Format32bppRgb);
Byte[] bytes = new byte[WIDTH * HEIGHT * 4];
BitmapToByteArray(bitmap, bytes);
private unsafe void BitmapToByteArray(Bitmap bitmap, Byte[] bytes)
{
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, WIDTH, HEIGHT), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
fixed(byte* pBytes = &bytes[0])
{
MoveMemory(pBytes, bitmapData.Scan0.ToPointer(), WIDTH * HEIGHT * 4);
}
bitmap.UnlockBits(bitmapData);
}
[DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory", SetLastError = false)]
private static unsafe extern void MoveMemory(void* dest, void* src, int size);
最佳答案
嗯,使用 Marshal.Copy()
在这里会更明智,至少可以减少(一次性)查找 DLL 导出的成本。但仅此而已,它们都使用 C 运行时 memcpy()
函数。速度完全受 RAM 总线带宽限制,只有购买更昂贵的机器才能加快速度。
请注意,分析是棘手的,第一次访问位图数据会导致页面错误,从而将像素数据放入内存。这需要多长时间取决于您的硬盘正在做什么以及文件系统缓存的状态。
关于c# - 我可以更快地复制这个数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5163391/