【问题标题】:How to properly serialize bitmap in C#?如何在 C# 中正确序列化位图?
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-08-24
    • 2016-06-23
    • 2014-08-09
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 2016-02-09
    相关资源
    最近更新 更多