In this tutorial, we will learn how to create ASCII art using a programming language called Python. ASCII art is essentially graphics created using keyboard characters. These images can be used in a variety of ways, including in games or as a fun way to visualize data. Python is remarkably well-suited to creating ASCII art due to its ability to manipulate strings and lists.
Step 1: Use an Image
We are going to use the following image:
Step 2: Open and Convert The Image
Once you have installed Pillow, you can use it to open an image file and convert it into greyscale. This is done using the Image.open() and convert() methods. The following code demonstrates this:
1 2 3 4 5 |
from PIL import Image image_path = "robot.jpg" img = Image.open(image_path) img = img.convert('L') img.show() |
Step 3: Create The ASCII Art
The next step is to convert the greyscale image into ASCII art. This is accomplished by mapping the different greyscale values to different ASCII symbols. To keep the tutorial simple, we will use an 8-character ASCII mapping. Here’s how it’s done:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
ASCII_CHARS = '@%#*+=-:. ' img_width = 70 width, height = img.size img = img.resize((img_width, int(0.55 * img_width * height / width))) pixels = img.getdata() ascii_str = '' for pixel_value in pixels: ascii_str += ASCII_CHARS[pixel_value // 32] ascii_str_len = len(ascii_str) ascii_img="" for i in range(0, ascii_str_len, img_width): ascii_img += ascii_str[i:i + img_width] + "\n" print(ascii_img) |
Full code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
from PIL import Image image_path = "robot.jpg" img = Image.open(image_path) img = img.convert('L') ASCII_CHARS = '@%#*+=-:. ' img_width = 70 width, height = img.size img = img.resize((img_width, int(0.55 * img_width * height / width))) pixels = img.getdata() ascii_str = '' for pixel_value in pixels: ascii_str += ASCII_CHARS[pixel_value // 32] ascii_str_len = len(ascii_str) ascii_img="" for i in range(0, ascii_str_len, img_width): ascii_img += ascii_str[i:i+img_width] + "\n" print(ascii_img) |
Output
Conclusion
Creating ASCII Art with Python is as simple as that! With only a couple of lines of code, you have created a fun and unique representation of an image. This can be a great way to add an interesting visual element to your programs or projects.