當前位置:
首頁 > 知識 > c 操作圖片存入xml和顯示圖片

c 操作圖片存入xml和顯示圖片

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Xml;

using System.IO;

namespace WindowsFormsApp1

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

//彈出一個選擇文件的對話框

OpenFileDialog openFileDialog1 = new OpenFileDialog();

DialogResult ok = openFileDialog1.ShowDialog();

if (ok == DialogResult.OK)

{

try {

XmlDocument myXmlDoc = new XmlDocument();

//(bin目錄下放置一個標準的空的xml文件,命名為doc.xml)

myXmlDoc.Load(Application.StartupPath + "\doc.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());

}

}

}

private void button2_Click(object sender, EventArgs e)

{

try

{

//創建XmlDocument對象

XmlDocument doc = new XmlDocument();

//載入文件

doc.Load(Application.StartupPath + "\docSave.xml");

XmlNodeList nodeList = doc.GetElementsByTagName("image");

//得到該節點

XmlNode ImageNode = nodeList[0];

//得到節點內的二進位代碼

string PicByte = ImageNode.InnerXml;

//轉換為byte[]

byte[] b = Convert.FromBase64String(PicByte);

System.IO.MemoryStream sm = new MemoryStream();

//寫入到流中

sm.Write(b, 0, b.Length);

pictureBox1.Image = Image.FromStream(sm);

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

}

}

}

c 操作圖片存入xml和顯示圖片

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

Spark On Yarn 中出現的問題記錄
ELK日誌系統之通用應用程序日誌接入方案

TAG:程序員小新人學習 |