Search code examples
javafontsawtlwjgltruetype

Generating bitmap of a pixel style true type font (Java.awt)


I have some old school monospaced Amiga / Atari fonts in some various formats. Among them are ttf.

And i want to create the smallest possible size bitmap of the characters. (The "original" size in pixels). More accurately, the characters' smallest possible size.

So scaling it up from there (the quad of the character i'm rendering) should maintain the characters pixel-ratio and keep it sharp.

I could redraw the pixels to a png and manually map them myself. It wouldn't be the worst. But there should be a better way. I feel like the .ttf format wasn't really meant for small pixelated fonts. I'm not to familiar with other formats.

Maybe there is a way to extract the original pixel ratio of the characters from a .ttf?

I include some code for additional context. Just to show what i do and the classes i use now.

Creating the awt.Font. Where i want "fontSize" to be as described above:

InputStream stream = new FileInputStream(filePath);
Font font = Font.createFont(TRUETYPE_FONT,stream).deriveFont(PLAIN,fontSize);

From here i create a temporary BufferedImage, set up a Graphics2D context, set the font of the context and derive the FontMetrics.

BufferedImage image = new BufferedImage(1,1,BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics2D = image.createGraphics();
graphics2D.setFont(font);
FontMetrics metrics = graphics2D.getFontMetrics();

I use the tmp image to loop through the glyphs to determine the final Buffered image' width and height + the positional info of the characters in the final image. (code not shown)

Then create the final image:

image = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
graphics2D = image.createGraphics();
graphics2D.setFont(font);
graphics2D.setColor(Color.WHITE);

        for (char i = 0; i < font.getNumGlyphs(); i++) {
            if (font.canDisplay(i)) {
                Glyph glyph = characterMap.get(i);
                glyph.calculateTextureCoordinates(width,height);
                graphics2D.drawString(Character.toString(i), glyph.x,glyph.y);
            }
        }

Solution

  • I found a solution:

    "I want to create the smallest possible size bitmap of the characters. (The "original" size in pixels). More accurately, the characters' smallest possible size."

    "...maybe there is a way to extract the original pixel ratio of the characters from a .ttf?"

    One way of extracting the original pixel height is the website: fontdrop.info.

    Drag the .ttf file over and select "Data" panel. And scroll down to you see:

    enter image description here

    That would be the pixel height (of the tallest glyph). And when when using this (16) as the font-size parameter, gave me the original size.