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

本文关键字:序列化 位图 | 更新日期: 2023-09-27 18:32:26

>我有类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看起来已经损坏了。我做错了什么?如何正确操作?

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

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