我可以更快地复制这个数组吗?

tbr*_*dge 6 c# optimization copy bytearray bitmap

难道这就是绝对速度最快的,我可以有可能复制BitmapByte[]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);
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 6

好吧,使用Marshal.Copy()在这里会更明智,至少可以减少查找DLL导出的(一次)成本.但就是这样,它们都使用C运行时memcpy()功能.速度完全受RAM总线带宽限制,只需购买更昂贵的机器就可以加快速度.

请注意,分析很棘手,第一次访问位图数据会导致页面错误,从而将像素数据导入内存.这需要多长时间取决于您的硬盘正在做什么以及文件系统缓存的状态.


Ped*_*C88 -3

我认为这更快(我实际使用过它):

// Bitmap bytes have to be created via a direct memory copy of the bitmap
private byte[] BmpToBytes_MemStream (Bitmap bmp)
{
    MemoryStream ms = new MemoryStream();
    // Save to memory using the Jpeg format
    bmp.Save(ms, ImageFormat.Jpeg);

    // read to end
    byte[] bmpBytes = ms.GetBuffer();
    bmp.Dispose();
    ms.Close();

    return bmpBytes;
}
Run Code Online (Sandbox Code Playgroud)

原始来源