将图像插入XML文件

时间:2009-04-14 08:22:38

标签: xml image

我想在XML文件的元素中插入图像,这样做的最佳方法是什么?您能否建议一些将图像包含在xml文件中的好方法?

5 个答案:

答案 0 :(得分:21)

最常见的方法是将二进制文件作为base-64包含在元素中。但是,这是一种解决方法,并为文件添加了一些卷。

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

<xml><image>AAECAwQFBgcICQ==</image></xml>

如何执行此编码因架构而异。例如,使用.NET,您可以使用Convert.ToBase64StringXmlWriter.WriteBase64

答案 1 :(得分:4)

由于XML是一种文本格式,而图像通常不是(除了一些古老和古老的格式),因此没有真正合理的方法。查看ODT或OOXML等内容也会向您显示它们不会将图像直接嵌入到XML中。

然而,您可以将其转换为Base64或类似内容,并将其嵌入到XML中。

但是,在这种情况下,XML的空白处理可能会使事情变得更加复杂。

答案 2 :(得分:4)

XML不是用于存储图像的格式,也不是二进制数据。我认为这一切都取决于你想如何使用这些图像。如果您在Web应用程序中并希望从那里阅读并显示它们,我会存储URL。如果您需要将它们发送到另一个Web端点,我会将它们序列化,而不是手动将其保存在XML中。请解释一下情景。

答案 3 :(得分:4)

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

这也是Word的方式,因为它的XML文件(不是Word是如何使用XML的一个很好的例子:P)。

答案 4 :(得分:2)

以下是从Kirk Evans Blog获取的一些代码,演示了如何使用C#编码图像;

//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();
相关问题