用 XML 文件持久化和恢复图片信息

随便写写的一个例子:

        // 保存图片到 XML 文件
        private void Form1_Load(object sender, System.EventArgs e)
       
{
            Image img
= Image.FromFile(@"E:\MyDocs\My Pictures\样品.jpg");
            System.IO.MemoryStream stream
= new System.IO.MemoryStream();
            img.Save(stream, ImageFormat.Jpeg);
           
byte[] b = stream.GetBuffer();
           
string s = Convert.ToBase64String(b);

            XmlDocument doc
= new XmlDocument();
            doc.AppendChild(doc.CreateElement(
"image"));
            XmlElement elmtData
= doc.CreateElement("data");
            elmtData.InnerText
= s;
            doc.DocumentElement.AppendChild(elmtData);
            doc.Save(
"test.xml");
        }


       
// 从 XML 文件中读取图片信息
        private void button1_Click(object sender, System.EventArgs e)
       
{
            XmlDocument doc
= new XmlDocument();
            doc.Load(
"test.xml");
           
string s = doc.DocumentElement.SelectSingleNode("data").InnerText;
           
byte[] b = Convert.FromBase64String(s);
            MemoryStream stream
= new MemoryStream(b);
            Bitmap bitmap
= new Bitmap(stream);

           
this.pictureBox1.Image = bitmap;
        }
posted @ 2012-04-21 22:18  跟着阿笨一起玩.NET  阅读(374)  评论(0编辑  收藏  举报