Skip to content

Instantly share code, notes, and snippets.

@jrialland
Created February 3, 2025 13:44
Show Gist options
  • Save jrialland/7eeaff4904b285b281edd3e28a24bda5 to your computer and use it in GitHub Desktop.
Save jrialland/7eeaff4904b285b281edd3e28a24bda5 to your computer and use it in GitHub Desktop.
displays an image in the terminal
"""
try to display an image in terminal using vt100 256 color codes
"""
import os, sys
from PIL import Image
#~dep:colored
from colored import Back, Style
from typing import TextIO
def display_image(image:Image.Image, columns:int, output:TextIO, char_ratio:float=2.0) -> None:
image = image.convert('RGB')
width, height = image.size
aspect_ratio = height / width / char_ratio
new_width, new_height = columns, int(aspect_ratio * columns)
pixels = list(image.resize((new_width, new_height)).getdata())
output.write(
f'{Style.reset}\n'.join(
''.join(f'{Back.rgb(*pixels[y * new_width + x])} ' for x in range(new_width))
for y in range(new_height)
) + Style.reset
)
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: imgterm.py <image> <optional:columns>')
sys.exit(1)
image = Image.open(sys.argv[1])
if len(sys.argv) > 2:
cols = int(sys.argv[2])
else:
cols, _ = os.get_terminal_size()
display_image(image, cols, sys.stdout)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment