小编典典

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

c#

我想对一个复杂类型(类)进行 XML序列化 ,该 类型具有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序列化器序列化位图是行不通的,因为它没有公共的无参数构造函数,而默认的XML序列化器是必需的。

我知道以下几点:

  • 有一个解决方法,发布在这里:http : //www.dotnetspider.com/resources/4759-XML-Serialization-C-Part-II-Images.aspx 。但是,由于这包括添加其他属性,在我看来,这似乎有点hack。
  • 在sourceforge上还有一个深入的XML序列化项目。

我宁愿不引用其他项目,也不希望广泛地调整类,以仅允许这些位图的xml序列化。

有没有办法保持简单?

非常感谢,马塞尔


阅读 319

收藏
2020-05-19

共1个答案

小编典典

我会做类似的事情:

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