借助.NET Framework的Marshal.Copy方法,可以在DLL中快速高效地封送(marshaling)位图数据。
示例代码:
在DLL中:
public class BitmapMarshaller
{
public static byte[] MarshalBitmap(Bitmap bitmap)
{
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
byte[] buffer = new byte[bitmapData.Height * bitmapData.Stride];
Marshal.Copy(bitmapData.Scan0, buffer, 0, buffer.Length);
bitmap.UnlockBits(bitmapData);
return buffer;
}
public static Bitmap UnmarshalBitmap(byte[] buffer, int width, int height, PixelFormat pixelFormat)
{
Bitmap bitmap = new Bitmap(width, height, pixelFormat);
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat);
Marshal.Copy(buffer, 0, bitmapData.Scan0, buffer.Length);
bitmap.UnlockBits(bitmapData);
return bitmap;
}
}
在调用方的代码中:
Bitmap bitmap = new Bitmap("image.jpg");
byte[] buffer = BitmapMarshaller.MarshalBitmap(bitmap);
// 在此将 buffer 发送到其他进程
Bitmap receivedBitmap = BitmapMarshaller.UnmarshalBitmap(buffer, bitmap.Width, bitmap.Height, bitmap.PixelFormat);