Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

c# - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...