0

Possible Duplicate:
Serialize a Bitmap in C#/.NET to XML

I'm trying to serialize MyClass by using XmlSerializer, but looks like [XmlInclude(typeof(Bitmap))] doesn't works.

using System;
using System.Drawing;
using System.IO;
using System.Xml.Serialization;

class Program {
    static void Main() {
        var myClass = new MyClass {
            Name = "foo",
            MyImage = new Bitmap(@"e:\pumpkin.jpg")
        };

        var serializer = new XmlSerializer(typeof(MyClass));
        var fileStream = File.OpenWrite(@"e:\test.xml");
        serializer.Serialize(fileStream, myClass);
    }
}

[Serializable]
[XmlInclude(typeof(Bitmap))]
public class MyClass {
    public string Name { get; set; }
    public Bitmap MyImage { get; set; }
}

This is the resulting file:

<?xml version="1.0"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>foo</Name>
  <MyImage>
    <Palette />
  </MyImage>
</MyClass>
Community
  • 1
  • 1
Milos
  • 1,353
  • 2
  • 18
  • 37
  • Your question is answered here - http://stackoverflow.com/questions/1907077/serialize-a-bitmap-in-c-net-to-xml; the reason the default serialization doesn't work is because Bitmap doesn't have a default parameterless constructor. – dash Jan 15 '13 at 14:14

1 Answers1

1

You could make a property that get/sets your bitmap as a byte array. This should be base-64 encoded by the serializer.

public byte[] MyImageBytes {
    get {
       ImageConverter converter = new ImageConverter();
       return (byte[])converter.ConvertTo(MyImage, typeof(byte[]));
    }
}

You would probably also want to hide your Bitmap property with an [XmlIgnore] attribute. You may also want to prefer LinqToXml to the serializer as it gives you far more control.

Note that XmlSerializer performs quite badly when base-64 encoding. This is also the case for LinqToXml, the BitConverter class does a fine job converting to base-64 though.

Holstebroe
  • 4,993
  • 4
  • 29
  • 45