月耳思进

人生在世如身处荆棘之中,心不动,人不妄动,不动则不伤;如心动则人妄动,伤其身痛其骨,于是体会到世间诸般痛苦。
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

Posted on 2006-08-30 15:32  Xfan  阅读(221)  评论(0编辑  收藏  举报

读取图像

//定义图像源与目标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();