您的位置:首页 > 其它

.Net中将图片数据保存到XML文档

2005-04-07 10:37 267 查看
因为最近要做的项目中,我要通过XML动态生成窗体,看了UI图样,我有些叫苦:我通过XML动态生成窗体,可是主窗体中UI要用图标来确定要使用的窗体,怎么才能使主窗体的图标也是动态加载而且图标和要生成的窗体还有关联呢?我又想到用XML,查MSDN,看到只有XmlTextWriter和XmlTextReader里分别有XmlTextWriter.WriteBase64和XmlTextReader.ReadBase64可以操作图片这种二进制字节的数据。但是XmlTextWriter和XmlTextReader远不如XmlDocument操作方便,如果用这两者我就得写太多的代码。
困扰了我一天,记得以前看到过一篇文章介绍怎样将图片数据存储到Xml文件,可是怎么也找不到,后来终于在一个英文网站上找到了相关内容,而且还是2003年贴出来的,汗。
好了,不废话了,我把我的实现代码贴给大家吧。源代码下载

private XmlDocument document;
private string FilePath = Application.StartupPath + "\\..\\..\\FormStyle.xml"; // FormStyle.xml 文件地址

private void frmMain_Load(object sender, System.EventArgs e)

private void lbIcons_SelectedValueChanged(object sender, System.EventArgs e)

private void btnAdd_Click(object sender, System.EventArgs e)
{
// 如果不存在txtFilePath.Text所指文件,就退出
if(!File.Exists(txtFilePath.Text) || lbIcons.Items.Count == 0)
return;

if(lbIcons.SelectedIndex == -1)
lbIcons.SelectedIndex = 0;

if(document == null)
{
document = new XmlDocument();
document.Load(FilePath);
}

//Read the bitmap.
string data = null;
Bitmap bmp = new Bitmap(txtFilePath.Text);
using (MemoryStream mem = new MemoryStream())
{
bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Bmp);
// 将位图数据转换为Base64String放入字符串中
data = Convert.ToBase64String(mem.ToArray());
}

// 查找当前所选的窗体是否含有Image节点,若就新建一个
XmlNode node = document.DocumentElement.SelectSingleNode(string.Format("descendant::Form[@Name='{0}']", lbIcons.SelectedItem.ToString()));
XmlNode ImageNode = document.DocumentElement.SelectSingleNode(string.Format("descendant::Form[@Name='{0}']/Image", lbIcons.SelectedItem.ToString()));
if(ImageNode == null)
{
ImageNode = document.CreateElement("Image");
node.AppendChild(ImageNode);
}

// 将位图数据保存到XML文档
ImageNode.InnerText = data;
document.Save(FilePath);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐