我的课程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
看起来已损坏。我做错了什么?如何正确地做到这一点?
答案 0 :(得分:0)
Bitmap
班级有SerializableAttribute
,因此您可以直接序列化Bitmap
。序列化位图的方法中的相应代码是:
public Texture(SerializationInfo info, StreamingContext context)
{
Bitmap = (Bitmap)info.GetValue("Bitmap", typeof(Bitmap));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Bitmap", Bitmap);
}