chroma_rust/color/
mode.rs1use crate::Color;
2
3impl Color {
4 pub fn mode(&self, mode: &str) -> Vec<f64> {
8 match mode {
9 "rgb" => {
10 let (r, g, b) = self.rgb();
11 vec![r as f64, g as f64, b as f64]
12 }
13 "rgba" => {
14 let (r, g, b, a) = self.rgba();
15 vec![r as f64, g as f64, b as f64, a]
16 }
17 "lab" => {
18 let (l, a, b) = self.lab();
19 vec![l, a, b]
20 }
21 "hsl" => {
22 let (h, s, l) = self.hsl();
23 vec![h, s, l]
24 }
25 "hsv" => {
26 let (h, s, v) = self.hsv();
27 vec![h, s, v]
28 }
29 "cmyk" => {
30 let (c, m, y, k) = self.cmyk();
31 vec![c, m, y, k]
32 }
33 _ => todo!(),
34 }
35 }
36
37 pub fn vec_mode2color(vec_f64: Vec<f64>, mode: &str) -> Color {
38 let len = vec_f64.len();
39 match mode {
40 "rgb" => {
41 if len != 3 {
42 panic!(
43 "The {} mode must got a vec which len is 3, but got {}",
44 mode, len
45 )
46 }
47 let r = vec_f64[0].round() as u8;
48 let g = vec_f64[1].round() as u8;
49 let b = vec_f64[2].round() as u8;
50 Color::new(r, g, b, 1.0)
51 }
52 "rgba" => {
53 if len != 4 {
54 panic!(
55 "The {} mode must got a vec which len is 4, but got {}",
56 mode, len
57 )
58 }
59 let r = vec_f64[0].round() as u8;
60 let g = vec_f64[1].round() as u8;
61 let b = vec_f64[2].round() as u8;
62 let a = vec_f64[3];
63 Color::new(r, g, b, a)
64 }
65 "lab" => {
66 if len != 3 {
67 panic!(
68 "The {} mode must got a vec which len is 3, but got {}",
69 mode, len
70 )
71 }
72 let l = vec_f64[0];
73 let a = vec_f64[1];
74 let b = vec_f64[2];
75 let color_str = format!("lab({}, {}, {})", l, a, b);
76 Color::from(color_str.as_str())
77 }
78 "hsl" => {
79 if len != 3 {
80 panic!(
81 "The {} mode must got a vec which len is 3, but got {}",
82 mode, len
83 )
84 }
85 let h = vec_f64[0];
86 let s = vec_f64[1];
87 let l = vec_f64[2];
88 let color_str = format!("hsl({}, {}, {})", h, s, l);
89 Color::from(color_str.as_str())
90 }
91 "hsv" => {
92 if len != 3 {
93 panic!(
94 "The {} mode must got a vec which len is 3, but got {}",
95 mode, len
96 )
97 }
98 let h = vec_f64[0];
99 let s = vec_f64[1];
100 let v = vec_f64[2];
101 let color_str = format!("hsv({}, {}, {})", h, s, v);
102 Color::from(color_str.as_str())
103 }
104 "cmyk" => {
105 if len != 4 {
106 panic!(
107 "The {} mode must got a vec which len is 4, but got {}",
108 mode, len
109 )
110 }
111 let c = vec_f64[0];
112 let m = vec_f64[1];
113 let y = vec_f64[2];
114 let k = vec_f64[3];
115 let color_str = format!("cmyk({}, {}, {}, {})", c, m, y, k);
116 Color::from(color_str.as_str())
117 }
118 _ => todo!(),
119 }
120 }
121}