ASCII Art Generator
Abstract
Section titled “Abstract”ASCII art is the ancient practice of drawing pictures with text characters. It started in the typewriter era, exploded in the BBS days, and is still a charming way to dress up CLI tools, terminal banners, and Git commit messages. In this project you will build a Python ASCII Art Generator that turns any text into stylized character art with dozens of fonts, applies terminal colors, and saves the result to a file. Then we will go further — converting real images into ASCII using pixel brightness mapping.
You will learn:
- How to install and use external libraries (
pyfiglet,termcolor,colorama). - How fonts work in
pyfigletand where to discover the 500+ available ones. - How terminal colors are rendered with ANSI escape codes.
- How to save styled output to a plain-text file without color codes leaking in.
- How to turn a JPEG into ASCII using pixel-brightness mapping.
Prerequisites
Section titled “Prerequisites”- Python 3.6 or above.
- A code editor or IDE.
- A terminal that supports ANSI color codes (Windows Terminal, iTerm2, GNOME Terminal — anything modern).
Install Dependencies
Section titled “Install Dependencies”pip install pyfiglet termcolor coloramapyfiglet— Python port of the classic FIGlet program; provides the fonts.termcolor— convenience wrapper for ANSI color codes.colorama— makes ANSI codes work on legacy Windows terminals. (Optional on modern systems, but harmless.)
Getting Started
Section titled “Getting Started”Create the project
Section titled “Create the project”- Create a folder named
ascii-art-generator. - Inside it, create
asciiartgenerator.py.
Write the code
Section titled “Write the code”ASCII Art Generator
pch.viewSource# ASCII Art Generator
import pyfiglet # pip install pyfiglet
import termcolor # pip install termcolor
import colorama
import os
def asciiartgenerator():
print("ASCII Art Generator")
print("Enter the text to convert to ASCII Art: ")
text = input()
print("Enter the color of the text: ")
color = input()
print('''
3-d
3x5
5lineoblique
acrobatic
alligator
alligator2
alphabet
avatar
banner
banner3-D
banner3
banner4
barbwire
basic
bell
big
bigchief
binary
block
bubble
bulbhead
calgphy2
caligraphy
catwalk
chunky
coinstak
colossal
computer
contessa
contrast
cosmic
cosmike
cricket
cursive
cyberlarge
cybermedium
cybersmall
diamond
digital
doh
doom
dotmatrix
drpepper
eftichess
eftifont
eftipiti
eftirobot
eftitalic
eftiwall
eftiwater
epic
fender
fourtops
fuzzy
goofy
gothic
graffiti
hollywood
invita
isometric1
isometric2
isometric3
isometric4
italic
ivrit
jazmine
jerusalem
katakana
kban
larry3d
lcd
lean
letters
linux
lockergnome
madrid
marquee
maxfour
mike
mini
mirror
mnemonic
morse
moscow
nancyj-fancy
nancyj-underlined
nancyj
nipples
ntgreek
o8
ogre
pawp
peaks
pebbles
pepper
poison
puffy
pyramid
rectangles
relief
relief2
rev
roman
rot13
rounded
rowancap
rozzo
runic
runyc
sblood
script
serifcap
shadow
short
slant
slide
slscript
small
smisome1
smkeyboard
smscript
smshadow
smslant
smtengwar
speed
stampatello
standard
starwars
stellar
stop
straight
tanja
tengwar
term
thick
thin
threepoint
ticks
ticksslant
tinker-toy
tombstone
trek
tsalagi
twopoint
univers
usaflag
wavy
weird
''')
print("Enter the font style: ")
font = input()
asciiart = pyfiglet.figlet_format(text, font=font)
colored_asciiart = termcolor.colored(asciiart, color=color)
print(colored_asciiart)
print("Do you want to save the ASCII Art? (y/n)")
save = input()
if save == 'y':
print("Enter the name of the file: ")
filename = input()
with open(filename, 'w') as f:
f.write(colored_asciiart)
print("File saved successfully!")
else:
print("File not saved!")
print("Do you want to clear the screen? (y/n)")
clear = input()
if clear == 'y':
os.system('cls')
else:
print("Thank you for using ASCII Art Generator!")
if __name__ == "__main__":
asciiartgenerator() Run it
Section titled “Run it”C:\Users\Your Name\ascii-art-generator> python asciiartgenerator.py
ASCII Art Generator
Enter the text to convert to ASCII Art:
Hello
Enter the color of the text:
red
Enter the font style:
big
_ _ _ _
| | | | ___ | | | | ___
| |_| | / _ \ | | | | / _ \
| _ | | __/ | | | || (_) |
|_| |_| \___| |_| |_| \___/
Do you want to save the ASCII Art? (y/n)
y
Enter the name of the file:
hello.txt
File saved successfully!How it fits together
Section titled “How it fits together”Read from the top: this is what runs when you execute the file, and which function calls which. It is generated from the code, so it cannot drift from it.
flowchart TD
RUN(["python asciiartgenerator.py"])
asciiartgenerator("asciiartgenerator")
RUN --> asciiartgenerator
Step-by-Step Explanation
Section titled “Step-by-Step Explanation”1. Imports
Section titled “1. Imports”import pyfiglet
import termcolor
import colorama
import os
colorama.init() # Windows ANSI shim — harmless elsewherecolorama.init() swaps sys.stdout for a translating wrapper that turns ANSI codes into Windows console API calls on older Windows. On modern terminals it is a no-op.
2. Collect text, color, font
Section titled “2. Collect text, color, font”text = input("Text: ")
color = input("Color: ")
font = input("Font (e.g. big, slant, banner): ")termcolor accepts: grey, red, green, yellow, blue, magenta, cyan, white.
3. Generate the art
Section titled “3. Generate the art”ascii_art = pyfiglet.figlet_format(text, font=font)
print(termcolor.colored(ascii_art, color=color))figlet_format(text, font=...)returns a multi-line ASCII string.termcolor.colored(...)wraps it in ANSI codes for the requested color.
4. Save it
Section titled “4. Save it”if input("Save? (y/n) ").lower() == "y":
filename = input("Filename: ")
with open(filename, "w", encoding="utf-8") as f:
f.write(ascii_art) # NOTE: plain art, no color codes
print("Saved.")Saving the uncolored version is intentional — ANSI escape codes look like garbage when opened in a text editor. If you really want the colors persisted, save with the escape codes included; viewing in cat will preserve them.
5. Optional: clear the screen
Section titled “5. Optional: clear the screen”if input("Clear screen? (y/n) ").lower() == "y":
os.system("cls" if os.name == "nt" else "clear")os.name == "nt" is True on Windows; otherwise we assume a Unix-like terminal.
Discovering Fonts
Section titled “Discovering Fonts”pyfiglet ships with around 500 fonts. List them all:
import pyfiglet
for f in pyfiglet.FigletFont.getFonts():
print(f)Or preview one:
print(pyfiglet.figlet_format("Hello", font="slant"))Memorable fonts to try: slant, big, banner, block, bubble, digital, doom, epic, isometric1, larry3d, lean, nancyj, ogre, roman, script, shadow, small, standard, starwars, stop.
Input Validation
Section titled “Input Validation”The naive script crashes on a misspelled font. Wrap it:
available = set(pyfiglet.FigletFont.getFonts())
while True:
font = input("Font: ").strip()
if font in available:
break
print(f"Unknown font '{font}'. Try one of: slant, big, banner, …")Same for color:
VALID_COLORS = {"grey","red","green","yellow","blue","magenta","cyan","white"}
while True:
color = input("Color: ").strip().lower()
if color in VALID_COLORS:
break
print(f"Pick one of: {', '.join(VALID_COLORS)}")Common Mistakes
Section titled “Common Mistakes”| Problem | Cause | Fix |
|---|---|---|
pyfiglet.FontNotFound | Misspelled font name | Validate against getFonts() |
KeyError: 'orange' | termcolor only knows eight colors | Use one of the supported names |
| Garbled colors on Windows | Old Windows terminal | colorama.init() once at startup |
Saved file has weird [31m characters | Saved the colored string | Save the plain ascii_art, not colored_ascii |
| Wide output wraps awkwardly | Terminal narrower than the font width | Use a narrower font (small, mini) or widen the terminal |
Variations to Try
Section titled “Variations to Try”1. Rainbow text
Section titled “1. Rainbow text”Cycle through colors line by line:
COLORS = ["red","yellow","green","cyan","blue","magenta"]
for i, line in enumerate(ascii_art.splitlines()):
print(termcolor.colored(line, COLORS[i % len(COLORS)]))2. Random font each run
Section titled “2. Random font each run”import random
font = random.choice(pyfiglet.FigletFont.getFonts())3. CLI flags with argparse
Section titled “3. CLI flags with argparse”python asciiartgenerator.py "Hello" --font slant --color red --out hello.txtUse Python’s argparse library instead of input().
4. Convert a real image to ASCII
Section titled “4. Convert a real image to ASCII”A real image becomes ASCII by mapping pixel brightness to characters from dark to light:
from PIL import Image
CHARS = "@%#*+=-:. " # dark → light
def image_to_ascii(path, width=80):
img = Image.open(path).convert("L") # grayscale
aspect = img.height / img.width
height = int(width * aspect * 0.55) # chars are taller than wide
img = img.resize((width, height))
out = []
for y in range(height):
row = "".join(CHARS[int(img.getpixel((x, y)) / 255 * (len(CHARS) - 1))]
for x in range(width))
out.append(row)
return "\n".join(out)
print(image_to_ascii("photo.jpg"))convert("L")turns the image to 8-bit grayscale (0–255).- We scale brightness into the index range of
CHARS. - The 0.55 factor compensates for terminal characters being roughly twice as tall as wide.
5. Animated text
Section titled “5. Animated text”import time, os
words = ["Hello", "World", "Python"]
for w in words:
os.system("cls" if os.name == "nt" else "clear")
print(pyfiglet.figlet_format(w, font="big"))
time.sleep(0.8)6. Banner in your shell prompt
Section titled “6. Banner in your shell prompt”Print a small ASCII banner from your .bashrc / PowerShell profile every time a new shell starts.
7. Web service
Section titled “7. Web service”Wrap with Flask (see Basic Web Server) so visitors POST text and get ASCII back.
8. GUI version
Section titled “8. GUI version”Tkinter with an entry field, a dropdown of fonts, a color picker, and a multi-line text widget showing the result.
How ANSI Colors Work
Section titled “How ANSI Colors Work”Behind the scenes, “red text” is a short escape sequence:
\x1b[31mHello\x1b[0m\x1bis the ESC character.[31msays “foreground = red”.[0mresets to default at the end.
Terminals interpret these codes and color the text; text files just show the raw characters. That is why we save the plain ASCII art to disk — to keep it portable.
Real-World Applications
Section titled “Real-World Applications”- CLI tool banners — projects like Docker, npm, and Git all print stylized ASCII at startup.
- README art — a one-line
pyfigletcall generates great GitHub headers. - CTF / hacking flair — security tools love a good banner.
- Image-to-ASCII previews for terminals that cannot render images.
- Email signatures in plain-text-only environments.
Educational Value
Section titled “Educational Value”- External library usage — installing, importing, reading docs.
- Terminal output — escape codes, cross-platform differences.
- File I/O — saving text safely.
- Image processing — converting pixel data to character art.
- User experience — validation, prompts, friendly error messages.
Next Steps
Section titled “Next Steps”- Add multi-line input support (until the user enters an empty line).
- Build the image-to-ASCII variation above into a separate command.
- Wrap in a CLI with argparse for power users.
- Combine with Tkinter to make a desktop banner-generator.
- Publish on PyPI as a
python asciibannercommand.
Conclusion
Section titled “Conclusion”You used three external libraries, generated styled text, saved it safely, and learned how terminals render color along the way. The same techniques (pixel-to-char mapping, escape sequences, font tables) underlie far more impressive demos — but every one of them starts with figlet_format("Hello", font="big"). Full source on GitHub. Find more visual projects on Python Central Hub.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading