将C#/ .NET中的位图序列化为XML

时间:2009-12-15 12:23:15

标签: c# xml-serialization bitmap

我希望 XML-Serialize 一个复杂类型(类),它具有System.Drawing.Bitmap 类型的属性。

    /// <summary>
    /// Gets or sets the large icon, a 32x32 pixel image representing this face.
    /// </summary>
    /// <value>The large icon.</value>
    public Bitmap LargeIcon { get; set; }

我现在发现使用默认的XML序列化程序序列化Bitmap不起作用,因为它没有公共无参数构造函数,这对于默认的xml序列化程序是必需的。

我知道以下内容:

我宁愿不想引用另一个项目,也不想广泛调整我的类,只允许这些位图的xml序列化。

有没有办法保持这么简单?

非常感谢,Marcel

4 个答案:

答案 0 :(得分:42)

我会做类似的事情:

[XmlIgnore]
public Bitmap LargeIcon { get; set; }

[Browsable(false),EditorBrowsable(EditorBrowsableState.Never)]
[XmlElement("LargeIcon")]
public byte[] LargeIconSerialized
{
    get { // serialize
        if (LargeIcon == null) return null;
        using (MemoryStream ms = new MemoryStream()) {
            LargeIcon.Save(ms, ImageFormat.Bmp);
            return ms.ToArray();
        }
    }
    set { // deserialize
        if (value == null) {
            LargeIcon = null;
        } else {
            using (MemoryStream ms = new MemoryStream(value)) {
                LargeIcon = new Bitmap(ms);
            }
        }
    }
}

答案 1 :(得分:5)

您还可以实施ISerializable并使用SerializationInfo手动处理您的位图内容。

编辑:João是对的:处理XML序列化的正确方法是实现IXmlSerializable,而不是ISerializable

public class MyImage : IXmlSerializable
{
    public string Name  { get; set; }
    public Bitmap Image { get; set; }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        throw new NotImplementedException();
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        throw new NotImplementedException();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        writer.WriteStartElement("Name");
        writer.WriteString(this.Name);
        writer.WriteEndElement();

        using(MemoryStream ms = new MemoryStream())
        {
            this.Image.Save(ms, ImageFormat.Bmp );
            byte[] bitmapData = ms.ToArray();
            writer.WriteStartElement("Image");
            writer.WriteBase64(bitmapData, 0, bitmapData.Length);
            writer.WriteEndElement();
        }
    }
}

答案 2 :(得分:2)

BitMap类的设计并非易于XML序列化。所以,不,没有简单的方法来纠正设计决策。

答案 3 :(得分:2)

实施IXmlSerializable,然后自行处理所有序列化详细信息。

既然你说这是一个很大的类型而且你只对位图有问题,可以考虑这样做:

public class BitmapContainer : IXmlSerializable
{
    public BitmapContainer() { }

    public Bitmap Data { get; set; }

    public XmlSchema GetSchema()
    {
        throw new NotImplementedException();
    }

    public void ReadXml(XmlReader reader)
    {
        throw new NotImplementedException();
    }

    public void WriteXml(XmlWriter writer)
    {
        throw new NotImplementedException();
    }
}

public class TypeWithBitmap
{
    public BitmapContainer MyImage { get; set; }

    public string Name { get; set; }
}