ASCII Art Maker in Python

Updated: Nov 25, 2020

I recently found a website that converts Images into ascii art. I thought it was really cool and wanted to try to make one myself in python. Here's the result!

Original Image:

Final code:

from PIL import Image

image ="test.jpg", "r") # get image
brightness = ["@", "&", "%", "/", "~", ",", ".", " "] # brightness levels

pixels = list(image.getdata()) # get an array with rgb value for every pixel
width, height = image.size # get width and height of image
result = "" # final result will be stored in this variable

def inRange(min_val, max_val, val):
    if val >= min_val and val <= max_val:
        return True
    return False

for pixel in range(0, len(pixels)): #loop through all pixels

    #get current pixel color data as tuple e.g (255, 128, 50)
    current = pixels[pixel] 
    # convert value to black and white
    avg = (current[0] + current[1] + current[2]) // 3

    # checks if the current pixel number is a multiple of the width
    if (pixel % width) == 0: 
        result += "\n" # create new line in image
    #go through possible luminance values for the pixel      
    for x in range(0, len(brightness) + 1):
        # this part took me ages to get right
        if inRange(0, 255 // (len(brightness) - x), avg):
           result += brightness[-x - 1]
print(result) # print final result

Final result (a screen shot):

The image gets squashed because the new lines are taller than a character.

91 views0 comments

Recent Posts

See All