Terminal is a powerful tool. It is a text based interface to the system. It suuports ASCII characters. Some terminals support UTF-8 characters. Images, videos, animations, etc. are not supported on the terminal. But, we can still visualize animations on the terminal. In this article, we will see how to visualize animations on the terminal using Go programming language. The wrorking code is available on GitHub tasnimzotder/terminal-dance: Enjoy GIF animations in your terminal
We will visualize animations on the terminal using ASCII characters. So, our utlimate goal is to convert an image or GIF into ASCII characters. First of all, let's understand what ASCII characters are, then we will dig dive into the implementation.
ASCII stands for American Standard Code for Information Interchange. Now a days, ASCII is a part of Unicode. It occupies the first 128 codes in Unicode (U-00000000 to U-00000007F). ASCII characters are 7-bit characters. ASCII characters are used to represent English characters, numbers, and symbols. Some of the ASCII characters are shown in the table below.
Character | ASCII Code | Unicode Code |
---|---|---|
A | 65 | U+0041 |
B | 66 | U+0042 |
. | 46 | U+002E |
@ | 64 | U+0040 |
+ | 43 | U+002B |
Images are stored in the form of pixels, like cells in a matrix. Each pixel has a color. The color of the pixel is represented by a color code. An image can be colored or mono-chromatic. A colored image has three color codes for each pixel, one for red, one for green, and one for blue. A mono-chromatic image has only one color code for each pixel.
Enough of theory, let's see how to implement the idea. First we need to read the image or GIF. In case of GIF, we need to extract the frames. The image sizes can be very large. So, we need to resize the image.
After reading and resizing the image frames, we need to convert to three color channels into one. There are several methods to convert a color image to grayscale. Some of them are shown below.
In this article, we will use the luminosity method.
Now we have the grayscale image. We need to convert the grayscale image to ASCII characters. We will use a set of ASCII characters to represent the grayscale values. The ASCII characters are arranged in the increasing order of their intensity. The ASCII characters are shown below.
Some while spaces are added at the beginning of the string to make the thresholding easier. We will use the following formula to convert the grayscale value to ASCII character.
In this article, we have seen how to visualize animations on the terminal using ASCII characters. The working code is available on GitHub tasnimzotder/terminal-dance: Enjoy GIF animations in your terminal