Created
July 27, 2017 05:54
-
-
Save zhasm/98b04de3e86f1dde5926fd314e2750c6 to your computer and use it in GitHub Desktop.
A script for displaying image(s) on terminal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# extracted from celery | |
from __future__ import absolute_import, unicode_literals | |
import os | |
import sys | |
TERM = os.environ.get('TERM') | |
TERM_IS_SCREEN = TERM and TERM.startswith('screen') | |
_IMG_PRE = '\033Ptmux;\033\033]' if TERM_IS_SCREEN else '\033]' | |
_IMG_POST = '\a\033\\' if TERM_IS_SCREEN else '\a' | |
def isatty(fh): | |
try: | |
return fh.isatty() | |
except AttributeError: | |
pass | |
def supports_images(): | |
return isatty(sys.stdin) and os.environ.get('ITERM_PROFILE') | |
def _read_as_base64(path): | |
import codecs | |
import base64 | |
with codecs.open(path, mode='rb') as fh: | |
encoded = base64.b64encode(fh.read()) | |
return encoded if type(encoded) == 'str' else encoded.decode('ascii') | |
def imgcat(path, inline=1, preserve_aspect_ratio=0, **kwargs): | |
return '\n%s1337;File=inline=%d;preserveAspectRatio=%d:%s%s' % ( | |
_IMG_PRE, inline, preserve_aspect_ratio, | |
_read_as_base64(path), _IMG_POST) | |
if __name__ == '__main__': | |
if len(sys.argv) > 1: | |
for fn in sys.argv[1:]: | |
print(imgcat(fn)) | |
else: | |
print '\n'.join([i.strip() for i in """A script for displaying image(s) on terminal. | |
Usage: python {} <file1.png> [file2.png ...] | |
""".splitlines()]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment