DEV Community

loading...
Cover image for Create Ascii art with Python

Create Ascii art with Python

stokry profile image Stokry ・2 min read

Hello all, in today's quick tutorial I will show you a small Python script that converts image files into beautiful ASCII art.

This is our test image:

enter image description here
Let's jump to the code:

First we need to import our dependencies:

import sys
from PIL import Image
from termcolor import colored
import colorama
Enter fullscreen mode Exit fullscreen mode

First we need to read our image:

colorama.init()
try:
    image_path = sys.argv[1].strip('-')
except:
    image_path = input('test1.jpg')
Enter fullscreen mode Exit fullscreen mode

then we will be converting it into grayscale

class AsciiArt:
    def __init__(self, img_path):
        self.path = image_path
        self.img = Image.open(self.path)

    def image(self):
Enter fullscreen mode Exit fullscreen mode

after that, we resize the image:

        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)))
Enter fullscreen mode Exit fullscreen mode

new size of image, and we convert image to greyscale format

        img = img.convert('L')
        pixels = img.getdata()
Enter fullscreen mode Exit fullscreen mode

replace each pixel with a character from array

        chars = ["B", "S", "#", "&", "@", "$", "%", "*", "!", ":", "."]
        new_pixels = [chars[pixel//25] for pixel in pixels]
        new_pixels = ''.join(new_pixels)
Enter fullscreen mode Exit fullscreen mode

split string of chars into multiple strings of length equal to new width and create a list

        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)
Enter fullscreen mode Exit fullscreen mode

write to a text file.

      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"))
Enter fullscreen mode Exit fullscreen mode

Last step:

if __name__ == "__main__":
    AsciiArt(image_path).image()
Enter fullscreen mode Exit fullscreen mode

This is our final result -

enter image description here

Thank you all.

Discussion (0)

Forem Open with the Forem app