這是一個來自Android客戶端的示例XML文件。用二進制值更新一個xml文件
<test>
<to>Mee</to>
<from>Youuu</from>
<img src="http://www.domain.com/path/to/my/image.jpg" />
</test>
我已經寫了一個關於這個XML解析器。我的問題是,當它傳遞給Android客戶端,我需要有圖像二進制數據,而不是圖像路徑。我怎樣才能做到這一點,以及如何用二進制數據更新上述的XML。
這是一個來自Android客戶端的示例XML文件。用二進制值更新一個xml文件
<test>
<to>Mee</to>
<from>Youuu</from>
<img src="http://www.domain.com/path/to/my/image.jpg" />
</test>
我已經寫了一個關於這個XML解析器。我的問題是,當它傳遞給Android客戶端,我需要有圖像二進制數據,而不是圖像路徑。我怎樣才能做到這一點,以及如何用二進制數據更新上述的XML。
您可以使用Base64對圖像二進制數據進行編碼(以byte[]
表示),並將其作爲CDATA包含在xml中。 然後在Android機器上,您只需將它解碼爲一個字節數組,然後渲染圖像。
您可以使用Apache Commons進行編碼/解碼。
編輯:
你需要得到以將其轉換的圖像數據的字節表示。看我的例子。這是使用sun.misc.BASE64Decoder
和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上,你只需要檢索節點內容,並且像上面那樣對它進行解碼並按照你想要的圖像進行操作即可。
像JSON,Protocol Buffer這樣的XML替代品可以幫助您。
我確實得到了編碼,解碼......但表示的部分,我不明白......我該怎麼做更新? –
看到我的編輯,我已經包括了一個樣本 – Alex
感謝您的詳細信息亞歷克斯....這似乎很好,我接受它...將實施它,讓你知道雖然 –