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; }
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.
I am aware of the following:
I rather would not like referencing another project nor extensively tweak my class to just allow xml serialization of those bitmaps.
Is there no way to keep that simple?
Many thanks, Marcel
I would do something like:
[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); } } } }
You can also to implement ISerializable
and to use SerializationInfo
to deal manually with your bitmap content.
EDIT: João is right: Correct way to deal with XML serialization is to implement IXmlSerializable
, not 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(); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With