Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize a System.Windows.Media.ImageSource object

I am creating a chat application very basic. I establish the chat with a tcp connection. I often send serialized object through the network stream because it is simplier to program that way. anyways if I have a class person{ public string name{get;set;} } then it will be eassy to serialize that class. when I include a public ImageSource Img {get;set;} I am not able to serialize that class person any more.

the way I serialize is as:

Person p = new Person();
p.name = \\some name
p.Img = \\ some image

System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());

x.Serialize(connection.stream, p);//here is when the problem comes. I am not able to serialize it if I include an Img
like image 678
Tono Nam Avatar asked Aug 31 '11 19:08

Tono Nam


2 Answers

You can't serialize an image to XML, but you can save it to a MemoryStream and encode the binary data to base64.

string ImageToBase64(BitmapSource bitmap)
{
    var encoder = new PngBitmapEncoder();
    var frame = BitmapFrame.Create(bitmap);
    encoder.Frames.Add(frame);
    using(var stream = new MemoryStream())
    {
        encoder.Save(stream);
        return Convert.ToBase64String(stream.ToArray());
    }
}

BitmapSource Base64ToImage(string base64)
{
    byte[] bytes = Convert.FromBase64String(base64);
    using(var stream = new MemoryStream(bytes))
    {
        return BitmapFrame.Create(stream);
    }
}

Note that base64 is not very efficient in terms of space... If possible, it would be better to transmit the image in binary form, rather than in XML.

like image 75
Thomas Levesque Avatar answered Oct 26 '22 05:10

Thomas Levesque


your approach is correct but does not work anymore as soon as the class Person contains any non serializable object like in your case the ImageSource.

If I had to solve it staying close to your solution, I would store the byte[] of the image and parse it back after deserialization to reconstruct the ImageSource.

like image 29
Davide Piras Avatar answered Oct 26 '22 07:10

Davide Piras