日期:2014-03-30 浏览次数:21030 次
以前对于XML如何存储数据很感兴味,特别是看到一个文章说,可以直接用XML代替SQL server2000用来存储数据和交互数据,目前还在研讨之中。终于把如何存取图像到xml的代码搞定:)
读取图像
//定义图像源与目标xml文件
string ImgFileName = @"d:\中国挪动暴强广告.JPG";
string XmlFileName = @"D:\img.xml";
XmlTextWriter aXmlTextWriter = new XmlTextWriter(XmlFileName, System.Text.Encoding.Default);
aXmlTextWriter.Formatting = Formatting.Indented;
try
{
aXmlTextWriter.WriteStartDocument();
aXmlTextWriter.WriteComment("Contains a BinHex JPEG image");
aXmlTextWriter.WriteStartElement("jpeg");
//下边就是通用的读取图像的代码
System.IO.FileInfo fi = new System.IO.FileInfo(ImgFileName);
int size = (int)fi.Length;
//read the jpeg file
byte []img = new byte[size];
System.IO.FileStream fs = new System.IO.FileStream(ImgFileName, System.IO.FileMode.Open);
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
img = br.ReadBytes(size);
br.Close();
//留意这里用的是BinHex编码
aXmlTextWriter.WriteBinHex(img,0,size);
aXmlTextWriter.WriteEndDocument();
}
catch(XmlException xmlE)
{
Response.Write(xmlE.Message);
}
finally
{
aXmlTextWriter.Close();
}
显示图像
简单的在窗口中放一个PictureBox,在一个按钮中写如下代码
string XmlFileName = @"D:\img.xml";
XmlTextReader aXmlTextReader = new XmlTextReader(XmlFileName);
aXmlTextReader.Read();
aXmlTextReader.MoveToContent();
if(aXmlTextReader.LocalName == "jpeg")
{
System.IO.FileInfo fi = new System.IO.FileInfo(XmlFileName);
int iSize = (int)fi.Length;
byte []img = new byte[iSize];
aXmlTextReader.ReadBinHex(img,0,iSize);
//Byte to image object
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.Write(img,0,iSize);
Bitmap bmp = new Bitmap(ms);
ms.Close();
this.pictureBox1.Image = bmp;
}
aXmlTextReader.Close();
谢谢作者,哈哈,我“偷”过来,方便本人看;)