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

问题描述 投票:0回答:1

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

字体的每个字符,我想:

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

有人可以帮我向我展示一些关于上述目的的提示吗?

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

java fonts true-type-fonts
1个回答
3
投票

这会将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);

如果charactersMapString,或者

int charCode = (int) charactersMap[counter];

如果charactersMapchar阵列

希望这可以帮助

© www.soinside.com 2019 - 2024. All rights reserved.