Parent directory

catimg.sh

2432 bytes
 1################################################################################
 2# catimg script by Eduardo San Martin Morote aka Posva                         #
 3# https://posva.net                                                            #
 4#                                                                              #
 5# Output the content of an image to the stdout using the 256 colors of the     #
 6# terminal.                                                                    #
 7# GitHub: https://github.com/posva/catimg                                      #
 8################################################################################
 9
10# this should come from outside, either `magick` or `convert`
11# from imagemagick v7 and ahead `convert` is deprecated
12: ${CONVERT_CMD:=convert}
13
14function help() {
15  echo "Usage catimg [-h] [-w width] [-c char] img"
16  echo "By default char is \"  \" and w is the terminal width"
17}
18
19# VARIABLES
20COLOR_FILE=$(dirname $0)/colors.png
21CHAR="  "
22
23WIDTH=""
24IMG=""
25
26while getopts qw:c:h opt; do
27  case "$opt" in
28    w) WIDTH="$OPTARG" ;;
29    c) CHAR="$OPTARG" ;;
30    h) help; exit ;;
31    *) help ; exit 1;;
32    esac
33  done
34
35while [ "$1" ]; do
36  IMG="$1"
37  shift
38done
39
40if [ "$IMG" = "" -o ! -f "$IMG" ]; then
41  help
42  exit 1
43fi
44
45if [ ! "$WIDTH" ]; then
46  COLS=$(expr $(tput cols) "/" $(echo -n "$CHAR" | wc -c))
47else
48  COLS=$(expr $WIDTH "/" $(echo -n "$CHAR" | wc -c))
49fi
50WIDTH=$($CONVERT_CMD "$IMG" -print "%w\n" /dev/null)
51if [ "$WIDTH" -gt "$COLS" ]; then
52  WIDTH=$COLS
53fi
54
55REMAP=""
56if $CONVERT_CMD "$IMG" -resize $COLS\> +dither -remap $COLOR_FILE /dev/null ; then
57  REMAP="-remap $COLOR_FILE"
58else
59  echo "The version of convert is too old, don't expect good results :(" >&2
60  # $CONVERT_CMD "$IMG" -colors 256 PNG8:tmp.png
61  # IMG="tmp.png"
62fi
63
64# Display the image
65I=0
66$CONVERT_CMD "$IMG" -resize $COLS\> +dither `echo $REMAP` txt:- 2>/dev/null |
67sed -e 's/.*none.*/NO NO NO/g' -e '1d;s/^.*(\(.*\)[,)].*$/\1/g;y/,/ /' |
68while read R G B f; do
69  if [ ! "$R" = "NO" ]; then
70    if [ "$R" -eq "$G" -a "$G" -eq "$B" ]; then
71      ((
72      I++,
73      IDX = 232 + R * 23 / 255
74      ))
75    else
76      ((
77      I++,
78      IDX = 16
79      + R * 5 / 255 * 36
80      + G * 5 / 255 * 6
81      + B * 5 / 255
82      ))
83    fi
84    #echo "$R,$G,$B: $IDX"
85    echo -ne "\e[48;5;${IDX}m${CHAR}"
86  else
87    (( I++ ))
88    echo -ne "\e[0m${CHAR}"
89  fi
90  # New lines
91  (( $I % $WIDTH )) || echo -e "\e[0m"
92done