Convert Image to ASCII Art in Python
Convert any image to ASCII art by resizing, converting to grayscale, and mapping pixel brightness to characters using Pillow.
pip install Pillow
Python code
42 linesfrom PIL import Image
import sys
ASCII_CHARS = "@%#*+=-:. "
def resize_image(image, new_width=100):
"""Resize image maintaining aspect ratio."""
width, height = image.size
ratio = height / width
new_height = int(new_width * ratio * 0.55) # 0.55 adjusts for font aspect ratio
return image.resize((new_width, new_height))
def grayify(image):
"""Convert image to grayscale."""
return image.convert("L")
def pixels_to_ascii(image):
"""Convert grayscale pixels to ASCII characters."""
pixels = image.getdata()
return "".join(ASCII_CHARS[pixel // 25] for pixel in pixels)
def main(image_path, width=100):
try:
image = Image.open(image_path)
except Exception as e:
print(f"Unable to open image: {e}")
sys.exit(1)
image = resize_image(grayify(image), width)
ascii_str = pixels_to_ascii(image)
# Format into lines
pixel_count = len(ascii_str)
ascii_art = "\n".join(ascii_str[i:(i + width)] for i in range(0, pixel_count, width))
print(ascii_art)
if __name__ == "__main__":
if len(sys.argv) > 1:
main(sys.argv[1])
else:
print("Usage: python script.py <image_path> [width]")
Output
..---::----==--==--===++++==--:--:..
....:--::---===+++****##%#*++==--::..
....::-====+*#%%@@@@%%%%##*+==--:....
...::--===+*#%%@@@@@@@@%%%##*+==--:...
How it works
The script opens an image with Pillow, resizes it to a specified width while factoring font aspect ratio, and converts to grayscale. It maps each pixel's brightness (0–255) to one of ten ASCII characters from darkest to lightest. The resulting string is split into lines matching the desired output width, printed to the terminal.
Common mistakes
- Forgetting to install Pillow with pip install Pillow
- Using width that produces very tall/narrow output (adjust the 0.55 multiplier)
- Opening a path that doesn't exist or isn't an image (always catch exceptions)
Variations
- Use a different set of ASCII characters for more or less detail
- Write the ASCII art to a text file instead of printing it
Real-world use cases
- Generating banner art for a terminal-based game or CLI tool using any image input.
- Creating thumbnail previews of images in environments without GUI, such as SSH sessions.
- Adding a nostalgic, creative touch to personal projects or social media profiles.
Sponsored
More from Files & data
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a Python Script That Detects and Deletes Empty Files Across Folders easy
- Compare Two Folder Structures and Find Differences in Python easy
- Compress and Extract ZIP Files Programmatically in Python easy
- Convert CSV Files to JSON in Python easy
- Create a Personal Knowledge Base That Searches Notes Instantly in Python easy
Keep learning
Related tutorials and quizzes for this topic.