Hello fellow programmers! Recently I’ve been playing around with something called ASCII Art, really cool and simple algorithm for composing beautiful images from letters with specific shade of color. The effects are pretty awsome, after creating something like this, you can put it on t-shirt, canvas or wallpaper. And all of this will be done with a few lines of code in Python! Let’s get going with this guys!

1. Create ImageProcess class in Python

First we define our class with a constructor. As you can see, there are a few attributes in here! Self.chars is a string containing our core letters. Their order is not accidential. If you play around with it, you’ll notice, that this is the exact order of pixel saturation. Char_width and char_height are responsible for proper spacing between chars, it prevents our ASCII Art creations from scaling in an unwanted way.

class ImageProcess:

    def __init__(self):
        self.chars = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'."
        self.charArray = list(self.chars)
        self.charLength = len(self.charArray)
        self.interval = self.charLength / 256
        self.char_width, self.char_height = 5, 9
        self.char_ratio = self.char_width / self.char_height

2. Transforming picture into String

Next, we will add the core functionality of our algorithm. After this paragraph, you’ll be able to display an image as a String! If you display it in command line, you’ll notice, that it is already impressive! For now, we will add three methods:

  • matchingChar() – this function is responsible for picking the proper char from our “alphabet” String attribute
  • resize() – this function will resize our image to the desired dimensions. Remember, that each letter will correspond to one pixel, so if you leave the image in its original dimensions, you may get an enormous output
  • toGreyscale() – as the name says, this function turns image to grayscale, so that it only has one value on each pixel
    def matchingChar(self, inputInt):
        return self.charArray[math.floor(inputInt*self.interval)]

    def resize(self, image, new_width = 1000):
        width, height = image.size
        new_height = math.floor(height*(new_width/width)*self.char_ratio)
        return image.resize((new_width, new_height))

    def toGrayscale(self, image):
        return image.convert("L")

    def pixelToAscii(self, image):
        pixels = image.getdata()
        ascii_str = ""
        for pixel in pixels:
            ascii_str += self.matchingChar(pixel)
        return ascii_str

3. Last but not least…

We have to add a big function responsible for drawing pixels on new image canvas, with their color shades. On first glance this might look kinda complicated, however it’s not! First, you open a source file, that you want to transform into ASCII Art, then resize it. After that, you create a destination file with the dimensions of resized image and a desired background color. Lastly, you load pixels of resized image into array. Then that you just have to iterate over 2D pixel array and, based on the saturation of pixel, pick the right letter from “alphabet” String using matchingChar() function. Lastly you have to draw it on newly created canvas in appropreate color.

def processImage(self, filename, resolution, color):
        im = Image.open(os.path.join(os.getcwd(), filename))
        resized = self.resize(im, resolution)
        newImage = Image.new('RGBA', (resized.width*self.char_width, resized.height*self.char_height), color=color)
        img = ImageDraw.Draw(newImage)
        pixels = resized.load()
        for i in range(resized.height):
            for j in range(resized.width):
                r, g, b, a = pixels[j, i]
                print(r,b,g, a)
                img.text((j*self.char_width,i*self.char_height),self.matchingChar(math.floor((r+g+b)/3)),fill = (   r,g,b, a) )
        newImage.save("effect.png")

4. Summary

As you can see, with this simple script you can create really amazing stuff, everything is up to your creativity. Feel free to experiment with this code, as a form of excercise you might create ASCII Art gif creation algorithm! Hope you liked this post, see you in next one!

Also we encourage you to check out some of our videos on tiktok! https://www.tiktok.com/@asciiart_?