如何把一个图像存储到XML数据中,并读取出来


读取图像

//定义图像源与目标xml文件

string ImgFileName = @"d:\中国移动暴强广告.JPG";

string XmlFileName = @"D:\img.xml";

XmlTextWriter aXmlTextWriter = new XmlTextWriter(XmlFileName, System.Text.Encoding.Default);

aXmlTextWriter.Formatting = Formatting.Indented;

try

{

aXmlTextWriter.WriteStartDocument();

aXmlTextWriter.WriteComment("Contains a BinHex JPEG image");

aXmlTextWriter.WriteStartElement("jpeg");

//下边就是通用的读取图像的代码

System.IO.FileInfo fi = new System.IO.FileInfo(ImgFileName);

int size = (int)fi.Length;

//read the jpeg file

byte []img = new byte[size];

System.IO.FileStream fs = new System.IO.FileStream(ImgFileName, System.IO.FileMode.Open);

System.IO.BinaryReader br = new System.IO.BinaryReader(fs);

img = br.ReadBytes(size);

br.Close();

//注意这里用的是BinHex编码

aXmlTextWriter.WriteBinHex(img,0,size);

aXmlTextWriter.WriteEndDocument();

}

catch(XmlException xmlE)

{

Response.Write(xmlE.Message);

}

finally

{

aXmlTextWriter.Close();

}

显示图像

简单的在窗口中放一个PictureBox,在一个按钮中写如下代码

string XmlFileName = @"D:\img.xml";

XmlTextReader aXmlTextReader = new XmlTextReader(XmlFileName);

aXmlTextReader.Read();

aXmlTextReader.MoveToContent();

if(aXmlTextReader.LocalName == "jpeg")

{

System.IO.FileInfo fi = new System.IO.FileInfo(XmlFileName);

int iSize = (int)fi.Length;

byte []img = new byte[iSize];

aXmlTextReader.ReadBinHex(img,0,iSize);

//Byte to image object

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

ms.Write(img,0,iSize);

Bitmap bmp = new Bitmap(ms);

ms.Close();

this.pictureBox1.Image = bmp;

}

aXmlTextReader.Close();

优质内容筛选与推荐>>
1、HOJ 1225 Suptermarket(并查集)
2、基于Fedora9.0和VMware6.5在Linux下的安装
3、零基础学习 Python 之数字与运算
4、OM Price Lists
5、使用mysql监视器即命令行下的mysql


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号