技术文章 > 如何序列化XML含有二进制数据的类?

如何序列化XML含有二进制数据的类?

2018-10-18 00:53

文档管理软件,文档管理系统,知识管理系统,档案管理系统的技术资料:
如何序列化XML含有二进制数据的类?

一些类中含有二进制的数据,比如Bitmap,以下代码演示如何进行二进制数据的序列化与反序列化。

一、以下代码实现序列化和反序列化Bitmap为XML

// 序列化Serialize
Bitmap corolla = new Bitmap(@“C:\corolla.jpg“, true); // some image file.
MemoryStream ms = new MemoryStream();
corolla.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xw.Formatting = Formatting.Indented;
XmlSerializer ser = new XmlSerializer(ms.GetBuffer().GetType());
ser.Serialize(xw, ms.GetBuffer());
Console.WriteLine(“Serialized Content::“);
string sSerializedContent = sw.GetStringBuilder().ToString();
Console.WriteLine(sSerializedContent);
xw.Close();

//反序列化Deserialize
XmlTextReader xrw = new XmlTextReader(new StringReader(sSerializedContent));
corolla = new Bitmap(
new MemoryStream((byte[])ser.Deserialize(xrw)));
corolla.Save(“<new file name to check what it writes>“);
xrw.Close();

二、其他解决方法

可以通过Bitmap的Save()方法把字节数据保存到Memory Stream(byte[]数组格式),然后序列化byte数组,通常的做法是用System.Convert.ToBase64String()把字节数组转换为64位字符串。

另外可以通过以下方法恢复Bitmap:
{
System.IO.
return theImage;
}

三、如果使用.NET 3.0则可以用一下方法:

If you are using .NET 3.0, then you can take advantage of the DataContractSerializer to serialize Bitmaps and any other Serializable type:

Code Snippet

System.IO; System.Drawing; System.Runtime.Serialization; System.Text; System.Collections.Generic;

namespace

{

class Program
{
static void Main(string[] args)
{
Bitmap bitmap = new Bitmap(@“c:\users\me\pictures\test.bmp“);
DataContractSerializer dcs = new DataContractSerializer(typeof(Bitmap));
dcs.WriteObject(File.Create(“test.xml“), bitmap);
}
}
}
BitmapSerializationTest System;

public Bitmap SetImage(string Base64Image)MemoryStream ImageStream = new System.IO.MemoryStream(System.Convert.FromBase64String(Base64Image));
Bitmap theImage = new Bitmap(ImageStream);

:)