選擇自 xinyuxin912 的 Blog
將圖片讀入到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());
}