將圖片讀入到Dom中,并將其存為xml文件
發(fā)表時(shí)間:2024-02-03 來(lái)源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]1、需要命名空間using System.Text;using System.IO;using System.Xml;2、文件夾中存在001.jpg圖片3、生成一個(gè)docSave.xml文件//******************try { XmlDocument myXmlDoc = ...
1、需要命名空間
using System.Text;
using System.IO;
using System.Xml;
2、文件夾中存在001.jpg圖片
3、生成一個(gè)docSave.xml文件
//******************
try
{
XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.LoadXml("<picture><name>picture</name></picture>");
XmlElement elem = myXmlDoc.CreateElement("image");
// 打開圖片文件,利用該圖片構(gòu)造一個(gè)文件流
FileStream fs = new FileStream("../../001.jpg",FileMode.Open);
// 使用文件流構(gòu)造一個(gè)二進(jìn)制讀取器將基元數(shù)據(jù)讀作二進(jìn)制值
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("讀寫結(jié)束!");
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
//*************
//生成后的Xml文檔
//******
<picture>
<name>picture</name>
<image>......</image>
</picture>
//***********
//測(cè)試上一程序
//***********
說(shuō)明:讀取docSave.xml中的image節(jié)點(diǎn),將其存為圖片格式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("讀寫結(jié)束!");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}