如何在C#中正确序列化位图?

时间:2014-11-30 08:52:28

标签: c# .net serialization bitmap deserialization

我的课程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看起来已损坏。我做错了什么?如何正确地做到这一点?

1 个答案:

答案 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);   
}