using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//弹出一个选择文件的对话框
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult ok = openFileDialog1.ShowDialog();
if (ok == DialogResult.OK)
{
try {
XmlDocument myXmlDoc = new XmlDocument();
//(bin目录下放置一个标准的空的xml文件,命名为doc.xml)
myXmlDoc.Load(Application.StartupPath + "\\doc.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());
}
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
//创建XmlDocument对象
XmlDocument doc = new XmlDocument();
//载入文件
doc.Load(Application.StartupPath + "\\docSave.xml");
XmlNodeList nodeList = doc.GetElementsByTagName("image");
//得到该节点
XmlNode ImageNode = nodeList[0];
//得到节点内的二进制代码
string PicByte = ImageNode.InnerXml;
//转换为byte[]
byte[] b = Convert.FromBase64String(PicByte);
System.IO.MemoryStream sm = new MemoryStream();
//写入到流中
sm.Write(b, 0, b.Length);
pictureBox1.Image = Image.FromStream(sm);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}