【发布时间】:2011-07-07 00:15:02
【问题描述】:
这是绝对最快的我可以可能将Bitmap复制到C#中的Byte[]吗?
如果有更快的方法我很想知道!
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);
【问题讨论】:
-
不要使用
WIDTH * HEIGHT * 4来计算位图的大小。使用bitmapData.Stride * HEIGHT。即使行有填充,它也可以工作。 -
我知道,这只是一个例子。不过谢谢:)
-
你知道实际上有一个位图构造函数可以让你为位图提供自己的缓冲区吗?这可能是一个固定的托管数组。
-
@jdv-Jan de Vaan -- 是的,但我打算走另一条路。我有一个位图,需要一个字节数组。
标签: c# optimization bitmap copy bytearray