Skip to content

Instantly share code, notes, and snippets.

@gsampallo
Last active May 7, 2022 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsampallo/f775758cb12848e0830ca85e1c8e5620 to your computer and use it in GitHub Desktop.
Save gsampallo/f775758cb12848e0830ca85e1c8e5620 to your computer and use it in GitHub Desktop.
Asciiart
# Code from https://dev.to/stokry/create-ascii-art-with-python-31nd
import sys
from PIL import Image
from termcolor import colored
import colorama
colorama.init()
image_path = 'test.jpg'
class AsciiArt:
def __init__(self, img_path):
self.path = image_path
self.img = Image.open(self.path)
def image(self):
width, height = self.img.size
aspect_ratio = height/width
new_width = 120
new_height = aspect_ratio * new_width * 0.55
img = self.img.resize((new_width, int(new_height)))
img = img.convert('L')
pixels = img.getdata()
chars = ["B", "S", "#", "&", "@", "$", "%", "*", "!", ":", "."]
new_pixels = [chars[pixel//25] for pixel in pixels]
new_pixels = ''.join(new_pixels)
new_pixels_count = len(new_pixels)
ascii_image = [new_pixels[index:index + new_width]
for index in range(0, new_pixels_count, new_width)]
ascii_image = "\n".join(ascii_image)
print(ascii_image)
file = "ascii_image.txt"
with open(file, "w") as f:
f.write(ascii_image)
print(colored(f"saved art image to file as {file}", "yellow"))
if __name__ == "__main__":
AsciiArt(image_path).image()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment