【问题标题】:Insert images to XML file将图像插入 XML 文件
【发布时间】:2013-06-07 19:49:39
【问题描述】:

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

【问题讨论】:

    标签: xml image


    【解决方案1】:

    执行此操作的最常见方法是将二进制作为 base-64 包含在元素中。不过,这是一种解决方法,会增加文件的体积。

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

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

    如何进行此编码的方式因架构而异。例如,对于 .NET,您可以使用 Convert.ToBase64StringXmlWriter.WriteBase64

    【讨论】:

      【解决方案2】:

      由于 XML 是一种文本格式,而图像通常不是(除了一些古老和古老的格式),因此没有真正明智的方法来做到这一点。查看像 ODT 或 OOXML 之类的东西也表明它们不会将图像直接嵌入到 XML 中。

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

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

      【讨论】:

      • 我说的是“另存为'XML'”时可以获得的Word XML文件。
      • 我的立场是正确的。但是,我从未见过有人使用它(更不用说在野外看到此类文件了)。
      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          【解决方案5】:

          这里有一些取自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();
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-02-07
            • 1970-01-01
            • 1970-01-01
            • 2022-11-07
            • 1970-01-01
            • 1970-01-01
            • 2016-07-14
            • 2020-10-17
            相关资源
            最近更新 更多