序列化一个对象System.Windows.Media.ImageSource [英] Serialize a System.Windows.Media.ImageSource object
问题描述
我创建一个聊天应用程序非常基本的。我建立聊天用的TCP连接。我经常通过网络流发送序列化对象,因为它是simplier以这种方式进行编程。反正如果我有一个类人{公共字符串名称{;设置;}}
那么这将是EASSY序列化该类。当我包括公开的ImageSource图{获取;设置;}
我无法序列化类的人更多。
我序列化方式是:
人员P =新的Person();
p.name = \\\\一些名
p.Img = \\\\的一些图像System.Xml.Serialization.XmlSerializer X =新System.Xml.Serialization.XmlSerializer(p.GetType());x.Serialize(connection.stream,P); //这里是当问题出现。我不能序列化,如果我包括图
您不能序列化到XML的图像,但你可以将它保存到的MemoryStream
和连接code中的二进制数据为base64。
字符串ImageToBase64(位图的BitmapSource)
{
变种EN codeR =新PngBitmapEn codeR();
VAR框架= BitmapFrame.Create(位图);
EN coder.Frames.Add(架);
使用(VAR流=新的MemoryStream())
{
EN coder.Save(流);
返回Convert.ToBase64String(stream.ToArray());
}
}的BitmapSource Base64ToImage(串的base64)
{
字节[]字节= Convert.FromBase64String的(Base64);
使用(VAR流=新的MemoryStream(字节))
{
返回BitmapFrame.Create(流);
}
}
注意的base64不是在空间上非常有效的。如果可能的话,这将是更好的图像以二进制形式发送的,而不是在XML中。
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
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.
这篇关于序列化一个对象System.Windows.Media.ImageSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!