ASCII ART GENERATOR Using Python

In this tutorial you will learn how to generate ASCII art from the image using Python Library called Pillow.

ASCII ART GENERATOR Using Python

Install our Module Pillow

pip install pillow

What is Pillow ?

Python Pillow library is a fork of an older library called PIL. PIL stands for Python Imaging Library, and it's the original library that enabled Python to deal with images

Lets Get Started:

Create a folder name it any name you like, then create the following

  1. images (folder)
  2. ascii    (folder)
  3. main.py

main.py:

import PIL.Image
import requests
import os, glob, time
from pyfiglet import figlet_format
import fcntl, termios, struct



th, tw, hp, wp = struct.unpack('HHHH',
fcntl.ioctl(0, termios.TIOCGWINSZ,
struct.pack('HHHH', 0, 0, 0, 0)))





SYMBOLS = ["@", "#", "S", "%", "!", "*", "+", ";", ":", ",", "."]

UNICODE = ["█", "█", "▓", "▓", "▒", "▒", "░", "░", "┉", "┉", " "]



def delt():
  files = glob.glob('images/*')
  for f in files:
    os.remove(f)

def gen_id():
    global uid
    res = requests.get("https://idgen.i-api.repl.co/uid?length=5").json()["id"]
    uid = res

def download(img_name, url):
    res = requests.get(url)
    f = open(f"images/{img_name}.png", "wb")
    f.write(res.content)
    f.close()
    PIL.Image.open(f"images/{img_name}.png").convert("RGBA").save(f"images/{img_name}.png")




def resize_image(image, new_width=100):
  width, height = image.size
  ratio = height / width / 1.65
  new_height = int(new_width * ratio)
  resized_image = image.resize((new_width, new_height))
  return(resized_image)

def grayify(image):
  grayscale_image = image.convert("L")
  return(grayscale_image)

def symbols_to_ascii(image):
  pixels = image.getdata()
  characters = "".join([SYMBOLS[pixel//25] for pixel in pixels])
  return(characters)

def unicode_to_ascii(image):
  pixels = image.getdata()
  characters = "".join([UNICODE[pixel//25] for pixel in pixels])
  return(characters)

  
def imageAscii(new_width=100):
  os.system("cls||clear")
  print("Please Use Fullscreen Mode")
  type = input("[1]: SYMBOLS ASCII ART\n[2]: UNICODE ASCII ART\n>>> ")
  if type == "1":
    url = input("Image URL\n>>> ")
    gen_id()
    try:
      download(uid, url)
      image = PIL.Image.open(f"images/{uid}.png")
    except Exception as e:
      print(f"\033[93m{e}\nYou are seeing this error because the image url is not accessible or the image type is not supported\nIgnore the Traceback Error.")
  
    new_image_data = symbols_to_ascii(grayify(resize_image(image)))
    pixel_count = len(new_image_data)
    ascii_image = "\n".join(new_image_data[i:(i+new_width)] for i in range(0, pixel_count, new_width))
    os.system("cls||clear")
    print(ascii_image)
    ft = open(f"ascii/{uid}.txt", "wb")
    ft.write(bytes(ascii_image, "UTF-8"))
    ft.close()
    delt()
  elif type == "2":
    url = input("Image URL\n>>> ")
    gen_id()
    try:
      download(uid, url)
      image = PIL.Image.open(f"images/{uid}.png")
    except Exception as e:
      print(f"\033[93m{e}\nYou are seeing this error because the image url is not accessible or the image type is not supported\nIgnore the Traceback Error.")
  
    new_image_data = unicode_to_ascii(grayify(resize_image(image)))
    pixel_count = len(new_image_data)
    ascii_image = "\n".join(new_image_data[i:(i+new_width)] for i in range(0, pixel_count, new_width))
    os.system("cls||clear")
    print(ascii_image)
    ft = open(f"ascii/{uid}.txt", "wb")
    ft.write(bytes(ascii_image, "UTF-8"))
    ft.close()
    delt()
  else:
    imageAscii()


def textAscii():
  os.system("cls||clear")
  gen_id()
  type = input("[1]: Standard Font\n[2]: Custom Font\n>>> ")
  if type == "1":
    text = input("Your Text\n>>> ")
    data = figlet_format(str(text), font="standard")
    os.system("cls||clear")
    print(data)
    fta = open(f"ascii/text-{uid}.txt", "wb")
    fta.write(bytes(data, "UTF-8"))
    fta.close()
  elif type == "2":
    styl = input("Font Name\n(Visit 'http://www.figlet.org/examples.html' for fonts!)\n>>> ")
    text = input("Your Text\n>>> ")
    try:
      data = figlet_format(str(text), font=styl)
      os.system("cls||clear")
      print(data)
      fta = open(f"ascii/text-{styl}-{uid}.txt", "wb")
      fta.write(bytes(data, "UTF-8"))
      fta.close()
    except:
      print(f"\33[31mError: {styl} is not a valid font!\33[37m")
      time.sleep(2)
      textAscii()
  else:
    textAscii()
    

def main():
  os.system("cls||clear")
  print("Select The Convertor:\n[1]: Image To Ascii\n[2]: Text To Ascii")
  con = input(">>> ")
  if con == "1":
    imageAscii()
  elif con == "2":
    print("Please Use Fullscreen Mode")
    textAscii()
  else:
    main()

main()

Code Explanation:

 The code starts by importing the PIL library.

 The code then imports requests and os, which are used to make a request for an image from the website of the company "Pil".

 Next, it imports glob and time, which are used to find all images on that site.

 Then it imports figlet_format so that we can use figlet formatting in our program.

 It also imports fcntl and termios so that we can control input/output devices like keyboards or screens with Python code.

 The next line is where we define some symbols: @, "#", S, "%", !, *, "+", ; , : , .

 These symbols will be used later in our program when creating text using pyfiglet format.

 Next comes a list of numbers representing keyboard keys (th=0-9).

 This list is followed by two lists of characters: one containing letters A-Z and another containing numbers 0-9 (tw=A-Z).

 Then there's a third list called hp=a-z+0-9w (hp stands for high pica) which contains all letter combinations not found in tw or th such as xyzzywxyzabcdefghijklmnopq

 The code is a program that will take an image and convert it to text.

 The code will use the requests library to get the URL of the image, then use PIL.Image to load it into memory.

 The loaded image will be passed as input into figlet_format which will create a string with all the symbols in it for output.

 The code starts by defining a function called delt().

 This function deletes all files in the images folder.

 The next function, gen_id(), generates an ID for the user.

 It requests this ID from a website and returns it to the program.

 The download() function downloads an image from a URL and saves it as "images/{img_name}.png".

 The resize_image() function resizes an image to new width of 100 pixels.

 The grayify() function converts any color into grayscale and returns that result back to the calling code.

 Finally, symbols_to-ascii() converts text into ASCII characters so they can be printed on screen or saved in a file without having to use unicode encoding (which is what you would need if you wanted to save them as UTF-8).

 The code is meant to take a string of text and convert it into an ASCII string.

 The code above can be used to make the following changes: Convert a string of text from Unicode to ASCII.

 Convert a string of text from ASCII to Unicode.

 The code starts by printing a message to the user that they should use fullscreen mode.

 Next, it asks for input from the user as to which type of image they want: SYMBOLS ASCII ART or UNICODE ASCII ART.

 If the user selects SYMBOLS ASCII ART, then it will ask them for an URL and download that image into memory using PIL's open function.

 If the user selects UNICODE ASCII ART, then it will generate a random ID number and try to download that image using PIL's open function.

 The code starts by importing two modules: sys and urllib2 .

 The sys module is used in order to print messages on screen while urllib2 is imported so that we can get an URL from our users input box when asking them
 what kind of art they want (SYMBOLS or UNICODE).

 After importing these two modules, there are three if statements inside of a try block.

 The first if statement checks whether our input was "1" meaning we wanted symbols ascii art or not; if so, then we call gen_id() which generates a random ID number between 1-1000 and tries downloading this image with PIL's open function.

 The code is a Python function that creates an image of the given input.

 The first line of code declares a variable called type with two possible values: SYMBOLS ASCII ART and UNICODE ASCII ART.

 The second line of code asks the user to enter their choice into the text field provided.

 If they choose SYMBOLS ASCII ART, then the third line will call the gen_id() function, which generates a unique ID for this particular image.

 This ID is used in later lines to download it from a URL and save it to disk as "images/{uid}.png".

 The "f" prefix indicates that this string should be saved as UTF-8 encoded Unicode text.

 The code starts by creating a new image data object.

 It then creates an ascii string that will be the output of the program.

 The code then prints out the ascii string, and clears the screen before printing it again.

 The next step is to create a new image object from our input image url using resize_image().

 This function takes in two arguments: width and height, which are both integers representing how many pixels wide and tall your original image was.

 After this, we can use grayify() to convert our color into grayscale (a black-and-white representation).

 Then we take all of these values and put them into symbols_to_ascii(), which converts each value into its corresponding ASCII character (e for example would become "e").
 Finally, we print out what's left over with len() so that we know how long our final string is going to be.

 The code will print the following to the screen: You are seeing this error because the image url is not accessible or the image type is not supported\nIgnore the Traceback Error.

 The code starts by defining a function called textAscii().

 This function is used to convert the inputted text into ascii.

 The code starts by calling the gen_id() function, which generates an id for the user.

 The uid variable is then assigned this generated id value.

 The next line of code opens up a file called "ascii/{uid}.txt" and writes out bytes(ascii_image, "UTF-8") to it.

 This will create an ASCII image with all of the characters in your inputted text converted into their corresponding ascii values.

 The code will generate a unique ID for the user and open up a text file with the name ascii/{uid}.txt.

 The code will then write out bytes of the image in UTF-8 to this file.

 Lastly, it will close the text file and delete itself from memory.

 The code is trying to open a file called "ascii/text-{uid}.txt" with the write() method.

 The text is then written to this file in UTF-8 format.

 The code displays the text in a custom font.

 The code starts by asking the user for their font name.

 The code then asks the user to input text, which is stored in a variable called text.

 The code then formats that text using figlet_format and saves it to a file with the filename ascii/text-{styl}-{uid}.txt where {styl} is replaced with whatever font name was entered earlier and {uid} is replaced with whatever unique identifier was entered earlier.

 Finally, this file is opened up in an editor program like Notepad++ or Sublime Text 2 and saved as UTF-8 so that it can be read on any computer without having to worry about encoding issues.

 The code attempts to output the following: Your Text >>> Hello World!
 Font Name >>> figlet

Code Explain by Denigma