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

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

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

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

我知道以下内容:

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

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

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

非常感谢,马塞尔

我会做的事情如下:

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

您还可以实现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(); } } } 

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

实现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; } }