读取图像
//定义图像源与目标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();
谢谢作者,哈哈,我“偷”过来,方便自己看;)