C#操作圖片存入XML和顯示XML圖片
在form上放入兩個按鈕和一個picturebox,picturebox屬性sizemode選擇zoom,防止圖片顯示不全。
開啟圖片,然後轉換為二進位制流儲存,xml儲存字串。二進位制流和字串也有轉換。
程式碼大部分都是不同格式的轉換。
private void button1_Click(object sender, EventArgs e)
{DialogResult oK = openFileDialog1.ShowDialog();
if (oK == DialogResult.OK)
{
try
{
XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.Load(Application.StartupPath + "\\pic.xml");
XmlElement elem = myXmlDoc.CreateElement("image");
// 開啟圖片檔案,利用該圖片構造一個檔案流
FileStream fs = new FileStream(openFileDialog1.FileName, 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(Application.StartupPath + "\\docSave.xml");
MessageBox.Show("讀寫結束!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
xml裡面圖片顯示,先把字串轉換為二進位制流,然後再存入byte陣列,然後換算為圖片格式。
private void button2_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(Application.StartupPath + "\\docSave.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);//寫到流中
pictureBox1.Image = Image.FromStream(sm);//picbox
}