0

这是一个来自Android客户端的示例XML文件。

<test>
<to>Mee</to>
<from>Youuu</from>
<img src="http://www.domain.com/path/to/my/image.jpg" />
</test>

我已经为此编写了一个 XML 解析器。我的问题是在将它传递给 Android 客户端时,我需要图像二进制数据而不是图像路径。我怎样才能做到这一点,我怎样才能用二进制数据更新上述 XML。

4

2 回答 2

2

您可以使用Base64对图像二进制数据(由 a 表示byte[])进行编码,并将其作为 CDATA 包含在 xml 中。然后在 Android 机器上,您只需将其解码为字节数组,然后渲染图像。

您可以使用Apache Commons进行编码/解码。

编辑:

您需要获取图像数据的字节表示形式才能对其进行转换。看我的例子。这是使用sun.misc.BASE64Decoderand sun.misc.BASE64Encoder,您可能需要根据您在 Android 上的使用情况进行调整(请参阅 Apache Commons)。

public class SO11096275 {
    public static byte[] readImage(URL url) throws IOException {
        final ByteArrayOutputStream bais = new ByteArrayOutputStream();
        final InputStream is = url.openStream();
        try {
            int n;
            byte[] b = new byte[4096];
            while ((n = is.read(b)) > 0) {
                bais.write(b, 0, n);
            }
            return bais.toByteArray();
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png");
        byte[] imgData = readImage(url);
        String imgBase64 = new BASE64Encoder().encode(imgData);
        System.out.println(imgBase64);
        byte[] decodedData = new BASE64Decoder().decodeBuffer(imgBase64);
        FileUtils.writeByteArrayToFile(new File("/path/to/wikipedia-logo.png"), decodedData); // apache commons
    }
}

然后你有你的图像数据作为一个字符串imgBase64,你只需要使用你想要的 DOM 实现将一个节点附加到你的 xml,例如 dom4j。有一些方法可以添加CDATA到 XML。最后,在您的 Android 上,您只需要检索节点内容,您就可以像上面那样对其进行解码,并对图像做您想做的事情。

于 2012-06-19T07:25:51.293 回答
0

像 JSON、Protocol Buffer 这样的 XML 替代品可以帮助您。

于 2012-06-19T07:48:41.040 回答