Java 解析 truetype 字体以将每个字符提取为图像及其代码

标签 java fonts truetype

是否有任何 java 库可用于从 true type 字体 (.ttf) 中提取每个字符?

字体的每个字符,我要:

  1. 将其转换成图片
  2. 提取其代码(例如:Unicode 值)

任何人都可以帮助向我展示有关上述目的的一些提示吗?

P.S:我想弄清楚,这个应用程序是如何制作的:http://www.softpedia.com/progScreenshots/CharMap-Screenshot-94863.html

最佳答案

这会将 String 转换为 BufferedImage:

public BufferedImage stringToBufferedImage(String s) {
    //First, we have to calculate the string's width and height

    BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics g = img.getGraphics();

    //Set the font to be used when drawing the string
    Font f = new Font("Tahoma", Font.PLAIN, 48);
    g.setFont(f);

    //Get the string visual bounds
    FontRenderContext frc = g.getFontMetrics().getFontRenderContext();
    Rectangle2D rect = f.getStringBounds(s, frc);
    //Release resources
    g.dispose();

    //Then, we have to draw the string on the final image

    //Create a new image where to print the character
    img = new BufferedImage((int) Math.ceil(rect.getWidth()), (int) Math.ceil(rect.getHeight()), BufferedImage.TYPE_4BYTE_ABGR);
    g = img.getGraphics();
    g.setColor(Color.black); //Otherwise the text would be white
    g.setFont(f);

    //Calculate x and y for that string
    FontMetrics fm = g.getFontMetrics();
    int x = 0;
    int y = fm.getAscent(); //getAscent() = baseline
    g.drawString(s, x, y);

    //Release resources
    g.dispose();

    //Return the image
    return img;
}

我认为没有办法获取所有字符,您必须创建一个 Stringchar 数组来存储您想要的所有字符转换为图像。

一旦您拥有包含要转换的所有键的 Stringchar[],您就可以轻松地对其进行迭代并调用 stringToBufferedImage方法,那么你就可以做

int charCode = (int) charactersMap.charAt(counter);

如果 charactersMap 是一个 String,或者

int charCode = (int) charactersMap[counter];

如果 charactersMap 是一个 char 数组

希望对你有帮助

关于Java 解析 truetype 字体以将每个字符提取为图像及其代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17282495/

相关文章:

css - 字体文件夹未正确链接

linux - 鬼脚本字体

fonts - PlayN 字体支持

java - Eclipse Java 中的自动换行?

java - 如何使用 Chrome webdriver 缩小页面

html - 包括粗体字体不起作用

c# - 在 C# winform 中,我得到了 : "only truetype fonts are supported. This is not a TrueType Font"

java - Java 中的线程说明

java - 检查 HashMap 中是否已存在某个值,如果存在则允许用户输入有效值

css - 避免使用WP SuperCache和CSS交付CDN字体