Hello everyone, hope you all are doing good. I would like to show you how to print images onto the console using Python. So, let's get started.
Before getting started, make sure to have pip and python installed in your system
Getting started
Install required packages
pip install pillow colr
Now, you have setup the development environment. Let's get into the code
First, import the necessary libraries. The script uses the pillow
library for Image processing
from PIL import Image
from colr import Colr
# Ask the user for image filename
image_path = input("Image:")
In this example, I am prompting the user to enter the filename for the image and collect it in the image_path
variable.
Next, open the image
image = Image.open(image_path)
Now that we have opened the image. we need to read the image and get the colors. For that, use
pixel_values = image.getdata()
The
image.getdata()
function returns a list of RGB or RGBA values.
Now, lets print the image
width, height = image.size
for index, character in enumerate(pixel_values):
if not isinstance(character, (tuple, list)):
continue
r, g, b = character[:-1]
if index % width == 0:
print("")
print(Colr().rgb(r, g, b, "\u2584"), end="")
Wait, let me explain.
width, height = image.size
This image.size
property is a tuple containing the width and the height of the image.
for index, character in enumerate(pixel_values):
if not isinstance(character, (tuple, list)):
continue
We loop through the list of rgb colors and make sure that all the values are either in the form of tuple or list.
r, g, b = character[:-1]
This line unpacks the tuple into variables for red(r
), green(g
) and blue(b
)
print(Colr().rgb(r, g, b, "\u2584"), end="")
This line prints a pixel onto the screen.
I have created a python library for printing images onto the console. Check out the GitHub repository
Installation
The package can be installed via pip
pip install terminal-img
Quick Start
The library is really simple to get started with. Here's is an example of how you display an image
from image import DrawImage
image = DrawImage.from_file("image.png")
image.draw_image()
You can also use a url if you dont have the file locally stored
image = DrawImage.from_url("url")
image.draw_image()
The library can also be used with PIL images
from PIL import Image
from image import DrawImage
img = DrawImage(Image.open("img.png"))
img.draw_image()
CLI
img <file or url>
Methods
image.DrawImage
-
image
: The PIL image -
size
(Optional[Tuple]
) : The size of the image to be displayed. Default: 24, 24
image.DrawImage.from_file
-
filename
: The name of the…
Please let me know what you thing. Hope you learned something new today. Thank you for reading :)
Top comments (0)