C#操作图片存入XML和显示XML图片

来源:互联网 发布:淘宝网支持的网上银行 编辑:程序博客网 时间:2024/06/03 19:25

在form上放入两个按钮和一个picturebox,picturebox属性sizemode选择zoom,防止图片显示不全。  

打开图片,然后转换为二进制流存储,xml存储字符串。二进制流和字符串也有转换。

代码大部分都是不同格式的转换。

private void button1_Click(object sender, EventArgs e)

        {
            DialogResult oK = openFileDialog1.ShowDialog();
            if (oK == DialogResult.OK)
            {
                try
                {
                    XmlDocument myXmlDoc = new XmlDocument();
                    myXmlDoc.Load(Application.StartupPath + "\\pic.xml");
                    XmlElement elem = myXmlDoc.CreateElement("image");
                    // 打開圖片文件,利用該圖片構造一個文件流
                    FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open);
                    // 使用文件流構造一個二進制讀取器將基元數據讀作二進制值
                    BinaryReader br = new BinaryReader(fs);


                    byte[] imageBuffer = new byte[br.BaseStream.Length];
                    br.Read(imageBuffer, 0, Convert.ToInt32(br.BaseStream.Length));
                    string textString = System.Convert.ToBase64String(imageBuffer);
                    fs.Close();
                    br.Close();


                    XmlText text = myXmlDoc.CreateTextNode(textString);
                    myXmlDoc.DocumentElement.AppendChild(elem);
                    myXmlDoc.DocumentElement.LastChild.AppendChild(text);


                    myXmlDoc.Save(Application.StartupPath + "\\docSave.xml");


                    MessageBox.Show("讀寫結束!");




                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }

        }

xml里面图片显示,先把字符串转换为二进制流,然后再存入byte数组,然后换算为图片格式。 

private void button2_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath + "\\docSave.xml");


            XmlNodeList NodeList = doc.GetElementsByTagName("image");//得到节点列表  


            XmlNode ImageNode = NodeList[0];//得到该节点  


            string PicByte = ImageNode.InnerXml;//得到节点内的二进制代码  


            byte[] b = Convert.FromBase64String(PicByte);//转化为byte[]  


            System.IO.MemoryStream sm = new MemoryStream();


            sm.Write(b, 0, b.Length);//写到流中  
            pictureBox1.Image = Image.FromStream(sm);//picbox 
        }

0 0
原创粉丝点击