PYTHON

Creating Images in Your Terminal with Python and Rich Pixels

A newer Python package called Rich Pixels allows you to create images in your terminal and display them. Darren Burns, one of the team members from the Textual project, created this package.

Anyway, let’s find out how to use Rich Pixels!

Installation

You can install Rich Pixels using Python’s pip utility. Here’s how:

python -m pip install rich-pixels

Once you have Rich Pixels installed, you can try it out!

Displaying Images in the Terminal

Rich Pixels lets you take a pre-existing image and show it in your terminal. The higher the image’s resolution, the better the output will be. However, if your image has too many pixels, it probably won’t fit in your terminal, and much of it will be drawn off-screen.

For this example, you will use the Python Show Podcast logo and attempt to draw it in your terminal.

Open up your favorite Python editor and add the following code to it:

from rich_pixels import Pixels
from rich.console import Console

console = Console()
pixels = Pixels.from_image_path("python_show200.jpg")
console.print(pixels)

For this example, you will use a square image that is 200×200 pixels. You can run the code like this in your terminal:

python pixels.py

When you execute the command above, you will see something like this in your terminal:

 

As you can see, the image is a little pixelated and gets cut off at the bottom. Of course, this all depends on your monitor’s resolution.

Here’s what happens when you use an image that is 80×80 pixels:

Rich pixel 80x80

You can also. use the Pillow package to create an image object and pass that the Rich Pixels too. Here’s how that might look:

with Image.open("path/to/image.png") as image: 
    pixels = Pixels.from_image(image)

You can create or draw your images using Pillow. There is some coverage of this topic in my article, Drawing Shapes on Images with Python and Pillow which you could then pass to Rich Pixels to display it.

Wrapping Up

Rich Pixels is a fun way to add extra pizzazz to your terminal applications. Rich Pixels can also be used in a Textual application. While there probably aren’t a lot of use cases for this package, it’s a lot of fun to play around with.

Give it a try, and let me know what you create!

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button