Skip to content

Instantly share code, notes, and snippets.

@scarolan
Forked from heptal/console_colors.md
Last active December 20, 2015 02:29
Show Gist options
  • Save scarolan/6057001 to your computer and use it in GitHub Desktop.
Save scarolan/6057001 to your computer and use it in GitHub Desktop.

Displaying images in the terminal with tput and echo

output

Requires ImageMagick, easily available from your favorite package manager. Tested on Linux and OSX
convert image.png -resize 40 txt:-|sed -E 's/://;s/\( ? ?//;s/, ? ?/,/g;s/\)//;s/(\w,\w,\w),\w/\1/g;/mage/d'|awk '{print $1,$2}'|python -c "import sys;f=sys.stdin.read().split('\n');f=filter(None,f);print 'tput rev;'+''.join([''.join(map(str,('echo;' if x.split(' ')[0].split(',')[0] is '0' else '','tput setaf '+str(sum(p*q for p,q in zip([36,6,1],[int(min(int(c),254)/42.5) for c in x.split(' ')[1].split(',')]))+16)+';echo -n \"  \";'))) for x in f])+'echo;tput sgr0'"|bash

Or, in your profile:

# Display image with tput
function image() {
convert "$1" -resize "$2" txt:-|sed -E 's/://;s/\( ? ?//;s/, ? ?/,/g;s/\)//;s/(\w,\w,\w),\w/\1/g;/mage/d'|awk '{print $1,$2}'|python -c "import sys;f=sys.stdin.read().split('\n');f=filter(None,f);print 'tput rev;'+''.join([''.join(map(str,('echo;' if x.split(' ')[0].split(',')[0] is '0' else '','tput setaf '+str(sum(p*q for p,q in zip([36,6,1],[int(min(int(c),254)/42.5) for c in x.split(' ')[1].split(',')]))+16)+';echo -n \"  \";'))) for x in f])+'echo;tput sgr0'"|bash
}

then, on file or url (replace 64 with the width you want):
image image.png 64

This one-liner has ImageMagick resize and convert the image into a list of pixel data, which are filtered and piped into inline python as a raw list of x,y r,g,b where rgb values are mapped to a terminal color space and then rendered into a string of tput and echo commands, which are finally executed by bash. Note that this violates every conceived notion of efficiency, practicality, readability and maintainability. If you have mission-critical terminal imaging needs, the caca-utils package can probably help.

The colors, which are the 'web-safe' colors, can be viewed here without ImageMagick:

n=6;for r in $(seq 16 $n 231);do echo "$(for c in $(seq $n);do v=$(($r + $c - 1));tput setaf $v && echo -ne $(printf "%03d" $v);echo -n ' '; done)";done

Comparison:

input output

Another fun example, <140 chars (no ImageMagick):

n=16;for r in $(seq 0 $n 255);do echo "$(for c in $(seq $n);do tput setaf $(($r + $c - 1)) && echo -ne '\xE2\x98\x85 ';done)";done

input

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment