Java parsing truetype font to extract each charact

2020-07-30 01:06发布

问题:

Is there any java library that can be used to extract each character from a true type font (.ttf)?

Each character of the font, I want to:

  1. Convert it to the image
  2. Extract its code (ex: Unicode value)

Anyone can help to show me some tips on above purpose?

P.S: I want to figure out, how such this app made: http://www.softpedia.com/progScreenshots/CharMap-Screenshot-94863.html

回答1:

This will convert a String to a 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;
}

I think there isn't a way to get all the characters, you have to create a String or a char array where you store all the chars you want to convert to image.

Once you have the String or char[] with all keys you want to convert, you can easily iterate over it and convert call the stringToBufferedImage method, then you can do

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

if charactersMap is a String, or

int charCode = (int) charactersMap[counter];

if charactersMap is a char array

Hope this helps