-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage.rs
58 lines (48 loc) · 1.43 KB
/
image.rs
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
use std::path::Path;
use color_thief::{Color, ColorFormat, get_palette};
use image::ColorType;
fn find_color(t: ColorType) -> ColorFormat {
match t {
ColorType::Rgb8 => ColorFormat::Rgb,
ColorType::Rgba8 => ColorFormat::Rgba,
_ => unreachable!(),
}
}
#[derive(Debug)]
pub struct Image<'a> {
path: &'a str,
}
impl<'a> Image<'a> {
pub fn new(path: &'a str) -> Self {
Image { path }
}
fn resolved_path(&self) -> &Path {
Path::new(&self.path)
}
pub fn palette(&self) -> Option<Vec<Color>> {
match image::open(self.resolved_path()) {
Ok(image) => {
let color_type = find_color(image.color());
let colors = get_palette(&image.into_bytes(), color_type, 10, 10).unwrap();
Some(colors)
}
Err(error) => {
match error {
image::ImageError::IoError(_error) => {
println!("Problem opening the file: {}", &self.path);
}
_ => {
panic!("Unexpected error when opening the file: {}", &self.path)
}
}
None
}
}
}
pub fn file_basename(&self) -> &str {
self.resolved_path().file_stem().unwrap().to_str().unwrap()
}
pub fn dominant_color(&self) -> Color {
self.palette().unwrap()[0]
}
}