我有一个base64编码的字体字符串
String font_data="font/truetype;charset=utf-8;base64,AAEAAAAMAIAAAwBAT1MvMmaobcEAAAFIAAAAVmNtYXCo5nJcAAACgAAAAVJnYXNw//8AAwAAKHQAAAAIZ2x5Zt1rdPEAAARIAAAULGhlYWTx2l1e ........... AFwAXQAAAAAAAf//AAI=";
现在我想使用.ttf
;
java
字体文件
怎么做?
提前致谢..
答案 0 :(得分:3)
只需解码base64部分并将其保存在文件中(我假设该部分实际上是True Type字体)。
如果您使用的是Java 7:
String fontData = "font/truetype;charset=utf-8;base64,QUJDREU= ... ";
fontData = fontData.substring(fontData.indexOf("base64,") + 7);
File ttFile = new File("/path/to/your/file.ttf");
try (FileOutputStream output = new FileOutputStream(ttFile)) {
byte[] binary = javax.xml.bind.DatatypeConverter.parseBase64Binary(fontData);
output.write(binary);
} catch (IOException e) {
e.printStackTrace();
}
如果您使用的是Java 6:
String fontData = "font/truetype;charset=utf-8;base64,QUJDREU= ... ";
fontData = fontData.substring(fontData.indexOf("base64,") + 7);
File ttFile = new File("/path/to/your/file.ttf");
try {
FileOutputStream output = null;
try {
output = new FileOutputStream(ttFile);
byte[] binary = javax.xml.bind.DatatypeConverter.parseBase64Binary(fontData);
output.write(binary);
} finally {
if(output != null) {
output.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
如果您使用的是旧版本,请下载并添加到类路径Apache Commons Codec,然后尝试:
String fontData = "font/truetype;charset=utf-8;base64,QUJDREU= ... ";
fontData = fontData.substring(fontData.indexOf("base64,") + 7);
File ttFile = new File("/path/to/your/file.ttf");
FileOutputStream output = null;
try {
try {
output = new FileOutputStream(ttFile);
byte[] binary = new org.apache.commons.codec.binary.Base64().decode(fontData);
output.write(binary);
} finally {
if(output != null) {
output.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}