Skip to content

Instantly share code, notes, and snippets.

@zhasm
Created July 27, 2017 05:54
Show Gist options
  • Save zhasm/98b04de3e86f1dde5926fd314e2750c6 to your computer and use it in GitHub Desktop.
Save zhasm/98b04de3e86f1dde5926fd314e2750c6 to your computer and use it in GitHub Desktop.
A script for displaying image(s) on terminal
# -*- 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