private void button1_Click(object sender, EventArgs e)
{
try{
int readByte = 0; //
int bytesToRead = 100;
string fileName = "../../yangm.xml";
// 打開圖片文件,利用該圖片構造一個文件流
FileStream fs = new FileStream("../../ym.jpg", FileMode.Open);
// 使用文件流構造一個二進制讀取器將基元數據讀作二進制值
BinaryReader br = new BinaryReader(fs);
XmlTextWriter xmlTxtWt = new XmlTextWriter(fileName, Encoding.UTF8);
//輸出設置代碼縮進
xmlTxtWt.Formatting = Formatting.Indented;
// xmlTxtWt.Indentation = 4;
xmlTxtWt.WriteStartDocument();
xmlTxtWt.WriteStartElement("picture", "ContactDetails", "http://www.deltabis.com/Contact");//定義命名空間
xmlTxtWt.WriteStartElement("image"); //定義節點
xmlTxtWt.WriteAttributeString("imageName", "002.jpg"); //添加圖片屬性
byte[] base64buffer = new byte[bytesToRead]; //開闢緩衝區
do
{
readByte = br.Read(base64buffer, 0, bytesToRead); //將數據讀入字節數組
xmlTxtWt.WriteBase64(base64buffer, 0, readByte); //將數組中二進制值編碼爲Base64並寫出到XML文件
} while (bytesToRead <= readByte);
xmlTxtWt.WriteEndElement();
xmlTxtWt.WriteEndElement();
xmlTxtWt.WriteEndDocument();
// xmlTxtWt.Flush();
xmlTxtWt.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
上邊的代碼是從網上找到的,下邊的代碼的功能爲如何從xml文件中把保存好的圖片提取出來
private void button2_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
//XmlNode d=new xmlnode
// 裝入指定的XML文檔
doc.Load("../../yangm.xml");
XmlNodeList NodeList = doc.GetElementsByTagName("image");//得到節點列表
XmlNode ImageNode = NodeList[0];//得到該節點
string PicByte = ImageNode.InnerXml;//得到節點內的二進制代碼
byte[] b = Convert.FromBase64String(PicByte);//轉化爲byte[]
System.IO.MemoryStream sm = new MemoryStream();
sm.Write(b, 0, b.Length);//寫到流中
this.photo.Image = Image.FromStream(sm);//picbox
base64簡介
Base64編碼把3個8位字節(3*8=24)轉化爲4個6位字節(4*6=24),之後在6位的前面補兩個0,形成8位一個字節的格式
base64把字節碼編程只包含a-zA-Z0-9+/這64個字符,所以稱爲base64