1

我有一个 base64 编码的字体字符串

String font_data="font/truetype;charset=utf-8;base64,AAEAAAAMAIAAAwBAT1MvMmaobcEAAAFIAAAAVmNtYXCo5nJcAAACgAAAAVJnYXNw//8AAwAAKHQAAAAIZ2x5Zt1rdPEAAARIAAAULGhlYWTx2l1e   ...........  AFwAXQAAAAAAAf//AAI=";

现在我想使用创建一个.ttf 字体文件java

这个怎么做?

提前致谢..

4

1 回答 1

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();
}
于 2013-06-24T10:12:41.187 回答