executable_color-converter 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/env bash
  2. # Summary: Converts colors from RGB to hexadecimal values and vice versa.
  3. # Usage: color-converter ff0000, color-converter 255 255 0 or
  4. # color-converter "#ffcc00"
  5. #
  6. # Feel free to contribute in any way at:
  7. # http://github.com/majjoha/color-converter
  8. # Check that a value is in range 0-255.
  9. valueInRange() {
  10. if [[ $1 =~ ^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$ ]]; then
  11. return 0
  12. else
  13. return 1
  14. fi
  15. }
  16. # Convert a color in RGB to a hexadecimal value.
  17. rgbToHex() {
  18. if valueInRange "$1" && valueInRange "$2" && valueInRange "$3"; then
  19. printf "rgb(%s, %s, %s) -> #%02X%02X%02X\n" "$1" "$2" "$3" "$1" "$2" "$3"
  20. else
  21. rangeError
  22. fi
  23. }
  24. # Darken a RGB color by percentage
  25. darkenRgb() {
  26. red=$(bc <<< "$1 + $4")
  27. green=$(bc <<< "$2 + $4")
  28. blue=$(bc <<< "$3 + $4")
  29. if [[ $(bc <<< "$red < 0") == 1 ]]; then
  30. red=0
  31. elif [[ $(bc <<< "$red > 255") == 1 ]]; then
  32. red=255
  33. fi
  34. if [[ $(bc <<< "$green < 0") == 1 ]]; then
  35. green=0
  36. elif [[ $(bc <<< "$green > 255") == 1 ]]; then
  37. green=255
  38. fi
  39. if [[ $(bc <<< "$blue < 0") == 1 ]]; then
  40. blue=0
  41. elif [[ $(bc <<< "$blue > 255") == 1 ]]; then
  42. blue=255
  43. fi
  44. printf "rgb(%s, %s, %s) -> rgb($red, $green, $blue)\n" "$1" "$2" "$3"
  45. }
  46. # Convert a hexadecimal color to RGB.
  47. hexToRgb() {
  48. if [[ ${1:0:1} == "#" ]]; then
  49. color=${1:1}
  50. else
  51. color=$1
  52. fi
  53. if ! [[ $color =~ ^[0-9A-Fa-f]{6}$ ]]; then
  54. rangeError
  55. else
  56. a=${color:0:2}
  57. b=${color:2:2}
  58. c=${color:4:2}
  59. printf "#$color -> rgb(%d, %d, %d)\n" 0x"${a}" 0x"${b}" 0x"${c}"
  60. fi
  61. }
  62. inputError() {
  63. echo "Bad input format. You should apply an argument like ff0000 or 255 255 0."
  64. exit 1
  65. }
  66. rangeError() {
  67. echo "Range input error. The input provided was out of range."
  68. exit 1
  69. }
  70. # Determine if we should run rgbToHex, hexToRgb or simply throw an error.
  71. if [[ "$#" == 3 ]]; then
  72. rgbToHex "$1" "$2" "$3"
  73. elif [[ "$#" == 1 ]]; then
  74. hexToRgb "$1"
  75. elif [[ "$#" == 4 ]]; then
  76. darkenRgb "$1" "$2" "$3" "$4"
  77. else
  78. inputError
  79. fi