├── README.md ├── dog.jpg └── img-viewer.py /README.md: -------------------------------------------------------------------------------- 1 | # Terminal Image Viewer 2 | 3 | >A Simple Python Script to Display Images in Linux Terminal 4 | 5 | 6 | ## Resources 7 | 8 | - [Formatted text in Linux Terminal](https://indianpythonista.wordpress.com/2017/04/02/formatted-text-in-linux-terminal-using-python/) 9 | 10 | - [ANSI color palette](https://kui.github.io/ansi_color_palette/) 11 | 12 | - [ANSI Color Specific RGB Sequence Bash](https://stackoverflow.com/a/26665998/8221580) 13 | 14 | 15 | ## Dependencies 16 | 17 | - pillow 18 | 19 | Install using pip: 20 | 21 | ``` 22 | $ pip install pillow 23 | ``` 24 | 25 | - numpy 26 | 27 | Install using pip: 28 | 29 | ``` 30 | $ pip install numpy 31 | ``` 32 | 33 | ## Usage 34 | 35 | ``` 36 | $ python img-viewer.py 37 | ``` 38 | 39 | For example: 40 | 41 | ``` 42 | $ python img-viewer.py dog.jpg 43 | ``` 44 | 45 | ## Tutorial 46 | 47 | [![](https://i.imgur.com/6dFbzca.png)](https://youtu.be/f77rKzqBzEA) -------------------------------------------------------------------------------- /dog.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikhilkumarsingh/terminal-image-viewer/99002327f93b2f577af68d8022646128b0797e11/dog.jpg -------------------------------------------------------------------------------- /img-viewer.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import numpy as np 3 | from PIL import Image 4 | 5 | 6 | def get_ansi_color_code(r, g, b): 7 | if r == g and g == b: 8 | if r < 8: 9 | return 16 10 | if r > 248: 11 | return 231 12 | return round(((r - 8) / 247) * 24) + 232 13 | return 16 + (36 * round(r / 255 * 5)) + (6 * round(g / 255 * 5)) + round(b / 255 * 5) 14 | 15 | 16 | def get_color(r, g, b): 17 | return "\x1b[48;5;{}m \x1b[0m".format(int(get_ansi_color_code(r,g,b))) 18 | 19 | 20 | def show_image(img_path): 21 | try: 22 | img = Image.open(img_path) 23 | except FileNotFoundError: 24 | exit('Image not found.') 25 | 26 | h = 100 27 | w = int((img.width / img.height) * h) 28 | 29 | img = img.resize((w,h), Image.ANTIALIAS) 30 | img_arr = np.asarray(img) 31 | h,w,c = img_arr.shape 32 | 33 | for x in range(h): 34 | for y in range(w): 35 | pix = img_arr[x][y] 36 | print(get_color(pix[0], pix[1], pix[2]), sep='', end='') 37 | print() 38 | 39 | 40 | if __name__ == '__main__': 41 | if len(sys.argv) > 1: 42 | img_path = sys.argv[1] 43 | show_image(img_path) --------------------------------------------------------------------------------