catimg.sh 2.4 KB

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