-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrgba2hex
executable file
·96 lines (83 loc) · 1.75 KB
/
rgba2hex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env bash
H_flag=false
usage() {
echo "
Usage: rgba2hex [OPTIONS] [RGBA CODE]
OPTIONS:
-H remove hashtag from output
RGBA CODE example:
rgb(255, 12, 0)
rgba(219, 200, 15, 0.2)"
}
while getopts "Hh" opt; do
case "${opt}" in
H) H_flag=true ;;
h)
usage
exit 0
;;
\?)
usage
exit 1
;;
esac
done
shift $((OPTIND -1))
round() {
echo $(printf %.$2f $(echo "scale=$2;(((10^$2)*$1)+0.5)/(10^$2)" | bc))
}
if [ -z "$1" ]; then
echo "Please provide rgba code"
exit 1
fi
rgbacheck=${1:0:4}
has_alpha=false
if [ $rgbacheck = "rgba" ]; then
has_alpha=true
elif [ $rgbacheck = "rgb(" ]; then
has_alpha=false
else
echo " Input is probably not an rgba code.
It should either be of the format rgba(rrr, ggg, bbb, a.aa) or rgb(rrr, ggg, bbb).
Terminating..."
exit 1
fi
rawcode=$(echo $1 | cut -d '(' -f2- | tr -d ')')
rawred=$(echo $rawcode | cut -d ',' -f1)
rawgreen=$(echo $rawcode | cut -d ',' -f2)
rawblue=$(echo $rawcode | cut -d ',' -f3)
if [ ${#rawred} == 1 ]; then
red=$(printf '0%x' $rawred)
else
red=$(printf '%x' $rawred)
fi
if [ ${#rawgreen} == 1 ]; then
green=$(printf '0%x' $rawgreen)
else
green=$(printf '%x' $rawgreen)
fi
if [ ${#rawblue} == 1 ]; then
blue=$(printf '0%x' $rawblue)
else
blue=$(printf '%x' $rawblue)
fi
if [ $has_alpha = true ]; then
rawalpha=$(echo $rawcode | cut -d ',' -f4)
rawalpha=$(round $(echo "$rawalpha * 255" | bc) 0)
if [ ${#rawalpha} == 1 ]; then
alpha=$(printf '0%x' $rawalpha)
else
alpha=$(printf '%x' $rawalpha)
fi
if ($H_flag); then
echo -n "$red$green$blue$alpha"
else
echo -n "#$red$green$blue$alpha"
fi
else
if ($H_flag); then
echo -n "$red$green$blue"
else
echo -n "#$red$green$blue"
fi
fi