Today, it is going to be less technical post. Some time ago I found my self getting into a problem to generate some instruction for CLI tool. What I was looking for is a simple way to generate fine ASCII art text just from string. So, I would like to show you a two ASCII art generators with Python3 right now. First is a simple generator from text input and second, a bit more completed from image.
As I said before, the simplest way to convert text to ASCII output is using figlet. There is a nice port called pyfiglet which make it possible to generate beautiful art just from text input just from console.
$ pip3 install pyfiglet
And just run it. The tool accepts a font family as input parameter:
$ result = pyfiglet.figlet_format("CyberTechTalk", font = "crazy")
And here we go!
Another way is leveraging Pillow
Image Library. This is a bit more laborious process.
1. First we have to load image and resize it:
import PIL.Image
def main():
image = PIL.Image.open(path)
def resize(image, newwidth = 100):
initwidth, initheight = image.size
newheight = newwidth * initheight / initwidth
return image.resize((newwidth, newheight))
2. After, convert image to grey scale:
def converttoascii(image):
pixels = image.getdata()
asciistr = "";
for pixel in pixels:
asciistr += ASCII_CHARS[pixel//25];
return asciistr
greyscaleimage = image.convert("L")
asciistr = converttoascii(greyscale_image)
3. Once we get the ASCII string of the image, we need to split the string based on the image’s width and save it in a file:
for i in range(0, len(asciistr), width):
img+= asciistr[i:i+width] + "\n"
#save the string to a file
with open(output.txt", "w") as f:
f.write(img);
This method allows to map any image to ASCII text and store to a text file.
For more interesting content please follow me on tweeter or subscribe not to miss anything.
Be an ethical, save your privacy!