colconv 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/bin/bash
  2. LANG=C # good for the printf version - see stackoverflow.com/a/8402305
  3. precision=3 # digits after the '.'
  4. grabber="grabc"
  5. function usage {
  6. echo "$1
  7. convert one 6 digit hex color
  8. to 3 rgb values between 0 and 1.
  9. argument: either one 6 digit hex color
  10. \"#nnnnnn\" (you must use quotes)
  11. or -g to grab with $grabber
  12. "
  13. exit 1
  14. }
  15. [[ $# != 1 ]] && usage "wrong number of arguments."
  16. if [[ "$1" == "-g" ]]; then
  17. if which $grabber >/dev/null 2>&1; then
  18. color="$($grabber 2>/dev/null)"
  19. else
  20. usage "$grabber not found in \$PATH."
  21. fi
  22. else
  23. [[ ! "$1" =~ ^#[0-9A-Fa-f]{6}$ ]] && usage "wrong format: $1"
  24. color="$1"
  25. fi
  26. red="$((16#${color:1:2}))"
  27. grn="$((16#${color:3:2}))"
  28. blu="$((16#${color:5:2}))"
  29. #~ for color in "$red" "$grn" "$blu"
  30. #~ do
  31. #~ bc<<<"scale=$precision;x=${color}/255;if(x>0 && x<1) print 0;print x"
  32. #~ ##~ bc<<<"ibase=16;obase=10;scale=$precision;${color}/FF"
  33. #~ done
  34. #~ bc<<<"scale=$precision;x=($red/255)*1.0;if(x>0 && x<1) print 0;print x"
  35. #~ printf ' '
  36. #~ bc<<<"scale=$precision;x=($grn/255)*1.0;if(x>0 && x<1) print 0;print x"
  37. #~ printf ' '
  38. #~ bc<<<"scale=$precision;x=($blu/255)*1.0;if(x>0 && x<1) print 0;print x"
  39. #~ printf '\n'
  40. # printf version
  41. printf "%${precision}.${precision}f " $(bc<<<"scale=$precision;$red/255")
  42. printf "%${precision}.${precision}f " $(bc<<<"scale=$precision;$grn/255")
  43. printf "%${precision}.${precision}f\n" $(bc<<<"scale=$precision;$blu/255")