iCeSnaker - Program rhapsody

谱写程序的狂想曲

导航

如何把一个图像存储到XML数据中,并读取出来

Posted on 2004-07-02 14:24  iCeSnaker  阅读(1225)  评论(1编辑  收藏  举报
以前对于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();

 



谢谢作者,哈哈,我“偷”过来,方便自己看;)