Want to turn any image into ASCII art? It's not magic, just simple brightness processing.
It's tedious and stupid to do it manually
img = [
[255, 0, 0],
[0, 255, 0]
]
# Now we need to pick a symbol for each pixel...
# What a hassle.Problem:
Manually selecting symbols by brightness is a pain. We need to automate the conversion of grayscale to symbols.
✔️ The right way (using gradation)
from PIL import Image
def image_to_ascii(path, width=100):
img = Image.open(path)
aspect = img.height / img.width
height = int(width * aspect * 0.55)
img = img.resize((width, height)).convert('L')
ascii_chars = '@%#*+=-:. '
pixels = img.getdata()
ascii_art = '\n'.join(
ascii_chars[pixel * (len(ascii_chars) - 1) // 255]
for pixel in pixels
)
lines = [ascii_art[i:i+width] for i in range(0, len(ascii_art), width)]
return '\n'.join(lines)
print(image_to_ascii('cat.jpg'))
How it works:
convert('L') converts the image to grayscale
Each pixel (0-255) is assigned a symbol from the set
The darker the pixel, the "denser" the symbol (e.g., '@'), the lighter - the "weaker" (space)
Let's write a converter with customizable palette:
class AsciiConverter:
PALETTES = {
'default': '@%#*+=-:. ',
'blocks': '█rayed ',
'detailed': '$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,"^`\'. '
}
def __init__(self, palette_name='default'):
if palette_name not in self.PALETTES:
raise ValueError(f'Нет такой палитры, идиот. Выбери из: {list(self.PALETTES.keys())}')
self.chars = self.PALETTES[palette_name]
def convert(self, image_path, width=80):
# ... code to convert using self.chars ...
return ascii_result
Try specifying a non-existent palette - you'll get a clear error.
Key parameters:
🔵Width - determines the size of the final ASCII art
🔵Character palette - affects the detail and style
🔵Aspect ratio - important for correct display
🔵Inversion - you can invert the brightness for a dark background
Important:
ASCII art isn't just a fun thing. It's used to visualize data in the console, create creative logs, and even "hide" information in plain sight.
👩💻 @CodeProgrammer
