Skip to content

Instantly share code, notes, and snippets.

@cstorey
Last active August 29, 2015 14:03
Show Gist options
  • Save cstorey/919e1b6689cd0ebb873a to your computer and use it in GitHub Desktop.
Save cstorey/919e1b6689cd0ebb873a to your computer and use it in GitHub Desktop.
Render an image in a 256 colour capable terminal.
#!/usr/bin/env bash
# Image viewer for terminals that support true colors.
# Copyright (C) 2014 Egmont Koblinger
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
if [ $# != 1 -o "$1" = "--help" ]; then
echo 'Usage: img.sh imagefile' >&2
exit 1
elif [ -z $(type -p convert) ]; then
echo 'Please install ImageMagick to run this script.' >&2
exit 1
fi
COLUMNS=$(tput cols)
declare -a upper lower
upper=()
lower=()
convert -thumbnail ${COLUMNS}x "$1" txt:- |
while IFS=',:() ' read col row dummy red green blue alpha rest; do
if [ "$col" = "#" -o "$row" = "#" ]; then
continue
fi
declare -a rgba
rgba=( $red $green $blue $alpha )
invalpha=$((255-$alpha))
for idx in 0 1 2; do
val=${rgba[$idx]}
fg=$((val*alpha))
bg=$((255*invalpha))
scaled=$(((fg+bg)/255))
rgba[$idx]=$scaled
done
color=$((16 + ((${rgba[0]}*6/256) * 36) + ((${rgba[1]}*6/256) * 6) + (${rgba[2]}*6/256)));
if [ $((row%2)) = 0 ]; then
upper[$col]="$color"
else
lower[$col]="$color"
fi
# After reading every second image row, print them out.
if [ $((row%2)) = 1 -a $col = $((COLUMNS-1)) ]; then
i=0
while [ $i -lt $COLUMNS ]; do
printf "\\e[38;5;${upper[$i]};48;5;${lower[$i]}m▀"
i=$((i+1))
done
# \e[K is useful when you resize the terminal while this script is still running.
printf "\\e[0m\e[K\n"
upper=()
d=()
fi
done
# Print the last half line, if required.
if [ "${upper[0]}" != "" ]; then
i=0
while [ $i -lt $COLUMNS ]; do
printf "\\e[38;5;${upper[$i]}m▀"
i=$((i+1))
done
printf "\\e[0m\e[K\n"
fi
Adapted for 256 color terminals from the 24-bit colour version at https://git.gnome.org/browse/vte/tree/perf/img.sh?h=vte-0-36 .
Original script (and this adaptation) licensed under GPLv2.
Octocat image used under presumed license from https://octodex.github.com/faq.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment