【发布时间】:2014-11-30 08:52:27
【问题描述】:
我有类Texture,其中包含System.Drawing.Bitmap Bitmap 和一些额外的数据和方法。我想把它序列化-反序列化成二进制文件,所以我这样实现ISerializable接口:
public Texture(SerializationInfo info, StreamingContext context)
{
PixelFormat pixelFormat = (PixelFormat)info.GetInt32("PixelFormat");
int width = info.GetInt32("Width");
int height = info.GetInt32("Height");
int stride = info.GetInt32("Stride");
byte[] raw = (byte[])info.GetValue("Raw", typeof(byte[]));
IntPtr unmanagedPointer = Marshal.AllocHGlobal(raw.Length);
Marshal.Copy(raw, 0, unmanagedPointer, raw.Length);
Bitmap = new Bitmap(width, height, stride, pixelFormat, unmanagedPointer);
Marshal.FreeHGlobal(unmanagedPointer);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("PixelFormat", (int)Bitmap.PixelFormat);
info.AddValue("Width", Bitmap.Width);
info.AddValue("Height", Bitmap.Height);
BitmapData data = Bitmap.LockBits(new Rectangle(0, 0, Bitmap.Width, Bitmap.Height), ImageLockMode.ReadOnly, Bitmap.PixelFormat);
info.AddValue("Stride", data.Stride);
byte[] raw = new byte[data.Height * Math.Abs(data.Stride)];
Marshal.Copy(data.Scan0, raw, 0, raw.Length);
info.AddValue("Raw", raw);
Bitmap.UnlockBits(data);
}
但在序列化和解散后Bitmap 看起来已损坏。我做错什么了?如何正确操作?
【问题讨论】:
-
您不能调用 Marshal.FreeHGlobal(),直到 位图被释放。是的,这非常痛苦。与其提供太多帮助,不如考虑使用 Image.Save() 保存到 MemoryStream 并序列化字节。用 MemoryStream 再次加载它,不要丢弃它。
标签: c# .net serialization bitmap deserialization