Read the image into Dom and save it as an xml file
1. Namespace required
using System.Text;
using System.IO;
using System .Xml;
2. The 001.jpg image exists in the folder
3. Generate a docSave.xml file
//********************************* { 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> //************************************************* //测试上一程序 //***********
Instructions: Read the image node in docSave.xml and save it as Image format 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()); }
The above is the content of reading the image into the Dom and saving it as an xml file. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!