Serialize a Bitmap in C#/.NET to XML(将 C#/.NET 中的位图序列化为 XML)

本文介绍了将 C#/.NET 中的位图序列化为 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要XML-Serialize一个复杂类型(类),它有一个System.Drawing.Bitmap类型的属性等等.

I want to XML-Serialize a complex type (class), that has a property of type System.Drawing.Bitmap among others.

    /// <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 序列化器所必需的.

I now have found out that serializing the Bitmap with the default XML serializer does not work, because it does not have a public parameterless constructor, which is mandatory with the default xml serializer.

我知道以下几点:

  • 存在一种变通方法,发布在此处:http://www.dotnetspider.com/resources/4759-XML-Serialization-C-Part-II-Images.aspx.但是,由于这包括添加另一个属性,这在我看来有点麻烦.
  • 在 sourceforge 上还有一个深度 XML 序列化项目.
  • There exists a workaround, posted here: http://www.dotnetspider.com/resources/4759-XML-Serialization-C-Part-II-Images.aspx . However since this includes adding another property this seems to me a bit of a hack.
  • There is also a deep XML serializing project on sourceforge.

我宁愿不喜欢引用另一个项目,也不喜欢大量调整我的类以只允许这些位图的 xml 序列化.

I rather would not like referencing another project nor extensively tweak my class to just allow xml serialization of those bitmaps.

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

非常感谢,马塞尔

推荐答案

我会这样做:

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

这篇关于将 C#/.NET 中的位图序列化为 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!