ASCII Art Generator
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 (
pyfigletpyfiglet,termcolortermcolor,coloramacolorama). - How fonts work in
pyfigletpyfigletand 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
- 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
pip install pyfiglet termcolor coloramapip install pyfiglet termcolor coloramapyfigletpyfiglet— Python port of the classic FIGlet program; provides the fonts.termcolortermcolor— convenience wrapper for ANSI color codes.coloramacolorama— makes ANSI codes work on legacy Windows terminals. (Optional on modern systems, but harmless.)
Getting Started
Create the project
- Create a folder named
ascii-art-generatorascii-art-generator. - Inside it, create
asciiartgenerator.pyasciiartgenerator.py.
Write the code
ASCII Art Generator
Source# 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()
# 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
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!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!Step-by-Step Explanation
1. Imports
import pyfiglet
import termcolor
import colorama
import os
colorama.init() # Windows ANSI shim — harmless elsewhereimport pyfiglet
import termcolor
import colorama
import os
colorama.init() # Windows ANSI shim — harmless elsewherecolorama.init()colorama.init() swaps sys.stdoutsys.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
text = input("Text: ")
color = input("Color: ")
font = input("Font (e.g. big, slant, banner): ")text = input("Text: ")
color = input("Color: ")
font = input("Font (e.g. big, slant, banner): ")termcolortermcolor accepts: greygrey, redred, greengreen, yellowyellow, blueblue, magentamagenta, cyancyan, whitewhite.
3. Generate the art
ascii_art = pyfiglet.figlet_format(text, font=font)
print(termcolor.colored(ascii_art, color=color))ascii_art = pyfiglet.figlet_format(text, font=font)
print(termcolor.colored(ascii_art, color=color))figlet_format(text, font=...)figlet_format(text, font=...)returns a multi-line ASCII string.termcolor.colored(...)termcolor.colored(...)wraps it in ANSI codes for the requested color.
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.")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 catcat will preserve them.
5. Optional: clear the screen
if input("Clear screen? (y/n) ").lower() == "y":
os.system("cls" if os.name == "nt" else "clear")if input("Clear screen? (y/n) ").lower() == "y":
os.system("cls" if os.name == "nt" else "clear")os.name == "nt"os.name == "nt" is True on Windows; otherwise we assume a Unix-like terminal.
Discovering Fonts
pyfigletpyfiglet ships with around 500 fonts. List them all:
import pyfiglet
for f in pyfiglet.FigletFont.getFonts():
print(f)import pyfiglet
for f in pyfiglet.FigletFont.getFonts():
print(f)Or preview one:
print(pyfiglet.figlet_format("Hello", font="slant"))print(pyfiglet.figlet_format("Hello", font="slant"))Memorable fonts to try: slantslant, bigbig, bannerbanner, blockblock, bubblebubble, digitaldigital, doomdoom, epicepic, isometric1isometric1, larry3dlarry3d, leanlean, nancyjnancyj, ogreogre, romanroman, scriptscript, shadowshadow, smallsmall, standardstandard, starwarsstarwars, stopstop.
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, …")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)}")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
| Problem | Cause | Fix |
|---|---|---|
pyfiglet.FontNotFoundpyfiglet.FontNotFound | Misspelled font name | Validate against getFonts()getFonts() |
KeyError: 'orange'KeyError: 'orange' | termcolor only knows eight colors | Use one of the supported names |
| Garbled colors on Windows | Old Windows terminal | colorama.init()colorama.init() once at startup |
Saved file has weird [31m[31m characters | Saved the colored string | Save the plain ascii_artascii_art, not colored_asciicolored_ascii |
| Wide output wraps awkwardly | Terminal narrower than the font width | Use a narrower font (smallsmall, minimini) or widen the terminal |
Variations to Try
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)]))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
import random
font = random.choice(pyfiglet.FigletFont.getFonts())import random
font = random.choice(pyfiglet.FigletFont.getFonts())3. CLI flags with argparse
python asciiartgenerator.py "Hello" --font slant --color red --out hello.txtpython asciiartgenerator.py "Hello" --font slant --color red --out hello.txtUse Python’s argparseargparse library instead of input()input().
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"))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")convert("L")turns the image to 8-bit grayscale (0–255).- We scale brightness into the index range of
CHARSCHARS. - The 0.55 factor compensates for terminal characters being roughly twice as tall as wide.
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)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
Print a small ASCII banner from your .bashrc.bashrc / PowerShell profile every time a new shell starts.
7. Web service
Wrap with Flask (see Basic Web Server) so visitors POST text and get ASCII back.
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
Behind the scenes, “red text” is a short escape sequence:
\x1b[31mHello\x1b[0m\x1b[31mHello\x1b[0m\x1b\x1bis the ESC character.[31m[31msays “foreground = red”.[0m[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
- CLI tool banners — projects like Docker, npm, and Git all print stylized ASCII at startup.
- README art — a one-line
pyfigletpyfigletcall 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
- 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
- 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 asciibannerpython asciibannercommand.
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")figlet_format("Hello", font="big"). Full source on GitHub. Find more visual projects on Python Central Hub.
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
