Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将图像插入到XML文件_Xml_Image - Fatal编程技术网

将图像插入到XML文件

将图像插入到XML文件,xml,image,Xml,Image,我想在XML文件的元素中插入一个图像,最好的方法是什么?您能推荐一些将图像包含到xml文件中的好方法吗?最常用的方法是将二进制文件作为base-64包含在元素中。但是,这是一种变通方法,会给文件增加一点容量 例如,这是字节00到09(注意,我们需要16个字节来编码10个字节的数据): AAECAwQFBgcICQ== 这种编码方式因体系结构而异。例如,对于.NET,您可以使用Convert.ToBase64String,或者XmlWriter.WriteBase64,因为XML是一种文本格式,

我想在XML文件的元素中插入一个图像,最好的方法是什么?您能推荐一些将图像包含到xml文件中的好方法吗?

最常用的方法是将二进制文件作为base-64包含在元素中。但是,这是一种变通方法,会给文件增加一点容量

例如,这是字节00到09(注意,我们需要16个字节来编码10个字节的数据):

AAECAwQFBgcICQ==

这种编码方式因体系结构而异。例如,对于.NET,您可以使用
Convert.ToBase64String
,或者
XmlWriter.WriteBase64

,因为XML是一种文本格式,而图像通常不是(除了一些古老的格式),所以没有真正明智的方法来这样做。看看像ODT或OOXML这样的东西,也会发现它们并没有将图像直接嵌入到XML中

但是,您可以将其转换为Base64或类似版本,并将其嵌入到XML中


然而,在这种情况下,XML的空白处理可能会使事情更加复杂。

XML不是存储图像的格式,也不是二进制数据。我认为这完全取决于你想如何使用这些图像。如果您在web应用程序中,并且希望从那里读取并显示它们,我会存储URL。如果需要将它们发送到另一个web端点,我将对它们进行序列化,而不是手动将它们持久化为XML。请解释是什么情况。

我总是将字节数据转换为Base64编码,然后插入图像


Word也是这样做的,因为它是XML文件(并不是说Word是如何使用XML:p的好例子)。

下面是一些代码,演示了如何用C#对图像进行编码


我说的是“另存为‘XML’”时可以得到的单词XML文件。我的观点是正确的。但是,我从来没有见过有人使用它(更不用说在野外看到这样的文件了)。
<xml><image>AAECAwQFBgcICQ==</image></xml>
//Load the picture from a file
Image picture = Image.FromFile(@"c:\temp\test.gif");

//Create an in-memory stream to hold the picture's bytes
System.IO.MemoryStream pictureAsStream = new System.IO.MemoryStream();
picture.Save(pictureAsStream, System.Drawing.Imaging.ImageFormat.Gif);

//Rewind the stream back to the beginning
pictureAsStream.Position = 0;
//Get the stream as an array of bytes
byte[] pictureAsBytes = pictureAsStream.ToArray();

//Create an XmlTextWriter to write the XML somewhere... here, I just chose
//to stream out to the Console output stream
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Console.Out);

//Write the root element of the XML document and the base64 encoded data
writer.WriteStartElement("w", "binData",
                         "http://schemas.microsoft.com/office/word/2003/wordml");

writer.WriteBase64(pictureAsBytes, 0, pictureAsBytes.Length);

writer.WriteEndElement();
writer.Flush();