Vale
Vale

Reputation: 3298

Serializing / Deserializing image to / from XElement

I am trying to serialize image into XElement and afterwards deserialize it for further use. I am using this method to serialize:

public XElement subElement = new XElement("Element");
private void Serialize(System.Windows.Forms.Button button) {
    if (button.Image != null) {
        var bf = new BinaryFormatter();
        var ms = new MemoryStream();
        bf.Serialize(ms, button.Image);
        var textWriter = new StringWriter();
        var writer = new XmlTextWriter(textWriter);
        byte[] imageBytes = ms.ToArray();
        writer.WriteBase64(imageBytes, 0, imageBytes.Length);
        subElement.Add(new XAttribute("Image", imageBytes));
    }
}

But I can't figure out how to deserialize. I tried something like this:

private void Deserialize(XElement element) {
    if (element.Attribute("Image") != null) {
        //tried XmlReader reader = XmlReader.Create(new StringReader(element.Attribute("Image").Value));
        //but reader is empty
        //when I try: XmlReader reader = XmlReader.Create(element.Attribute("Image").Value);
        //exception is thrown because XmlReader expects path, not element
    }
}

I basically only need to get byte array from XElement, later I know how to handle it.

Upvotes: 1

Views: 4175

Answers (2)

George Duckett
George Duckett

Reputation: 32438

Once you have your byte array you can do Convert.ToBase64String(byteArray). The result of that function (a string) is what goes in the XAttribute's value.

Then when it comes to reading, you'd just do byteArray = Convert.FromBase64String(element.Attribute("Image").Value)

This should prevent the issues with saving the string within the XML file.

Upvotes: 2

TcKs
TcKs

Reputation: 26632

Don't use serialization, simple save/load it from memory stream.

Upvotes: 0

Related Questions