将图片读入到Dom中,并将其存为xml文件
1、需要命名空间
using System.Text;
using System.IO;
using System.Xml;
2、文件夹中存在001.jpg图片
3、生成一个docSave.xml文件
//*********************************
{
XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.LoadXml("<picture><name>picture</name></picture>");
XmlElement elem = myXmlDoc.CreateElement("image");
// 打开图片文件,利用该图片构造一个文件流
FileStream fs = new FileStream("../../001.jpg",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("../../docSave.xml");
MessageBox.Show("读写结束!");
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
//************************************************
//生成后的Xml文档
//******
<picture>
<name>picture</name>
<image>......</image>
</picture>
//*************************************************
//测试上一程序
//***********
说明:读取docSave.xml中的image节点,将其存为图片格式002.jpg.
try
{
int readByte = 0;
int bytesToRead = 1044;
XmlTextReader xmlTxtRd = new XmlTextReader("../../docSave.xml");
FileStream fs = new FileStream("../../002.jpg",FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
byte[] base64buffer = new byte[bytesToRead];
while(xmlTxtRd.Read())
{
if (xmlTxtRd.NodeType == XmlNodeType.Element && xmlTxtRd.Name == "image")
{
do
{
readByte = xmlTxtRd.ReadBase64(base64buffer,0,bytesToRead);
bw.Write(base64buffer,0,readByte);
}
while( bytesToRead<= readByte);
}
}
bw.Flush();
bw.Close();
fs.Close();
xmlTxtRd.Close();
MessageBox.Show("读写结束!");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}