ASCII Art Generator Library in Java

ASCII art is a method of creating pictures using the normal printable characters used in computers (ASCII character set). ASCII art can be composed using normal text editors. However this process is very cumbersome. There are a number of software packages available that can convert images or text to ASCII art.

If you are looking for a programmatic ASCII art generator in Java just for text, check out the following Java program. This program can create ASCII art of any text using a number of fonts and in different sizes. You can also choose the symbol used for your ASCII art.

Download Source Code – ASCII Art Generator in Java

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

/**
 * ASCII Art Generator in Java. 
 * Prints a given text as an ASCII text art on the console. 
 * This code is licensed under - CC Attribution CC BY 4.0.
 * @author www.quickprogrammingtips.com
 *
 */
public class ASCIIArtGenerator {
    
    public static final int ART_SIZE_SMALL = 12;
    public static final int ART_SIZE_MEDIUM = 18;
    public static final int ART_SIZE_LARGE = 24;
    public static final int ART_SIZE_HUGE = 32;

    private static final String DEFAULT_ART_SYMBOL = "*";

    public enum ASCIIArtFont {
        ART_FONT_DIALOG("Dialog"), ART_FONT_DIALOG_INPUT("DialogInput"), 
        ART_FONT_MONO("Monospaced"),ART_FONT_SERIF("Serif"), ART_FONT_SANS_SERIF("SansSerif");

        private String value;

        public String getValue() {
            return value;
        }

        private ASCIIArtFont(String value) {
            this.value = value;
        }
    }

    public static void main(String[] args) throws Exception {
        ASCIIArtGenerator artGen = new ASCIIArtGenerator();
        
        System.out.println();
        artGen.printTextArt("Hello", ASCIIArtGenerator.ART_SIZE_MEDIUM);
        System.out.println();
        
        System.out.println();
        artGen.printTextArt("Love is life!", ASCIIArtGenerator.ART_SIZE_SMALL, ASCIIArtFont.ART_FONT_MONO,"@");
        System.out.println();
        
    }

    /**
     * Prints ASCII art for the specified text. For size, you can use predefined sizes or a custom size.
     * Usage - printTextArt("Hi",30,ASCIIArtFont.ART_FONT_SERIF,"@");
     * @param artText
     * @param textHeight - Use a predefined size or a custom type
     * @param fontType - Use one of the available fonts
     * @param artSymbol - Specify the character for printing the ascii art
     * @throws Exception
     */
    private void printTextArt(String artText, int textHeight, ASCIIArtFont fontType, String artSymbol) throws Exception {
        String fontName = fontType.getValue();
        int imageWidth = findImageWidth(textHeight, artText, fontName);

        BufferedImage image = new BufferedImage(imageWidth, textHeight, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        Font font = new Font(fontName, Font.BOLD, textHeight);
        g.setFont(font);

        Graphics2D graphics = (Graphics2D) g;
        graphics.drawString(artText, 0, getBaselinePosition(g, font));

        for (int y = 0; y < textHeight; y++) {
            StringBuilder sb = new StringBuilder();
            for (int x = 0; x < imageWidth; x++)
                sb.append(image.getRGB(x, y) == Color.WHITE.getRGB() ? artSymbol : " ");
            if (sb.toString().trim().isEmpty())
                continue;
            System.out.println(sb);
        }
    }

    /**
     * Convenience method for printing ascii text art.
     * Font default - Dialog,  Art symbol default - *
     * @param artText
     * @param textHeight
     * @throws Exception
     */
    private void printTextArt(String artText, int textHeight) throws Exception {
        printTextArt(artText, textHeight, ASCIIArtFont.ART_FONT_DIALOG, DEFAULT_ART_SYMBOL);
    }

    /**
     * Using the Current font and current art text find the width of the full image
     * @param textHeight
     * @param artText
     * @param fontName
     * @return
     */
    private int findImageWidth(int textHeight, String artText, String fontName) {
        BufferedImage im = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        Graphics g = im.getGraphics();
        g.setFont(new Font(fontName, Font.BOLD, textHeight));
        return g.getFontMetrics().stringWidth(artText);
    }

    /**
     * Find where the text baseline should be drawn so that the characters are within image
     * @param g
     * @param font
     * @return
     */
    private int getBaselinePosition(Graphics g, Font font) {
        FontMetrics metrics = g.getFontMetrics(font);
        int y = metrics.getAscent() - metrics.getDescent();
        return y;
    }
}

How ASCII Art Generator for Java Works?

ASCII art generator library for Java uses image drawing and image pixel detection to draw ASCII art. The algorithm for art generator is,

  • Using the selected font properties and ascii art size, calculate the width of the image required for printing the art text.
  • Using font properties, find the baseline position where the text should be drawn. This ensures that the drawn image is vertically centered.
  • Using Java awt API, draw the image corresponding to the art text. The image is drawn in white on a black background.
  • Iterate through the pixels of the image from top to bottom. Whenever a white pixel is detected, we add the art symbol otherwise we add a space.
  • Each row of pixels are then printed as a single line on the console. Voila! you now have the ascii art ready.

ASCII Art in Java – Samples

Following are some of the ASCII text art generated by the program,

artGen.printTextArt("Help", ASCIIArtGenerator.ART_SIZE_MEDIUM);
                          ***              
 ***     ***              ***              
 ***     ***              ***              
 ***     ***              ***              
 ***     ***     *****    ***   *** ***    
 ***     ***    *******   ***   ********   
 ***********   ****  ***  ***   **** ****  
 ***********   ***   ***  ***   ***   ***  
 ***     ***   *********  ***   ***   ***  
 ***     ***   *********  ***   ***   ***  
 ***     ***   ***        ***   ***   ***  
 ***     ***   ****       ***   ****  ***  
 ***     ***    ********  ***   ********   
 ***     ***     *******  ***   *** ***    
                                ***        
                                ***        
                                ***       

 

artGen.printTextArt("Java", 14,ASCIIArtFont.ART_FONT_DIALOG,"+");
  ++                          
  ++                          
  ++                          
  ++    ++++  ++     +  ++++  
  ++   +   ++  ++   +  +   ++ 
  ++       ++  ++   +      ++ 
  ++    +++++   ++ +    +++++ 
  ++   ++  ++   ++ +   ++  ++ 
  ++   ++  ++    ++    ++  ++ 
  ++    ++++++   ++     ++++++
  ++                          
+++                         

The ASCII art generator source code is licensed under Creative Commons Attribution. You can use the source code for anything as long as attribution link is given.

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply