我现在正在为用Java编写的电子书阅读器工作。主文件类型是fb2,它是基于XML的类型。
这些书中的图像以长文本行的形式存储在<binary>标记中(至少它看起来像文本编辑器中的文本)。
如何在Java中将此文本转换为实际的图片?为了使用XML,我使用了JDOM2库。
我尝试过的图片(jpeg文件)不是有效的:
private void saveCover(Object book) {
// Necessary cast to process with book
Document doc = (Document) book;
// Document root and namespace
Element root = doc.getRootElement();
Namespace ns = root.getNamespace();
Element binaryEl = root.getChild("binary", ns);
String binaryText = binaryEl.getText();
File cover = new File(tempFolderPath + "cover.jpeg");
try (
FileOutputStream fileOut = new FileOutputStream(cover);
BufferedOutputStream bufferOut = new BufferedOutputStream(
fileOut);) {
bufferOut.write(binaryText.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}发布于 2016-08-14 19:32:29
图像内容被指定为base64编码(参见:http://wiki.mobileread.com/wiki/FB2#Binary )。
因此,您必须从binary元素中获取文本并将其解码为二进制数据(在Java8中使用:java.util.base64和此方法:http://docs.oracle.com/javase/8/docs/api/java/util/Base64.html#getDecoder-- )
如果从代码中获取binaryText值,并将其提供给解码器的decode()方法,则应该为图像获得正确的byte[]值。
https://stackoverflow.com/questions/38941665
复制相似问题