diff --git a/Cargo.toml b/Cargo.toml index f3e8da9..61eeaed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ indicatif = { version = "0.17.8", features = ["rayon"] } kmeans_colors = "0.6.0" palette = "0.7.6" rayon = "1.10.0" +thiserror = "1.0.63" [profile.dev] debug = 0 diff --git a/Palettes/Palettes.html b/Palettes/Palettes.html index 6dbc56d..81a4c4b 100644 --- a/Palettes/Palettes.html +++ b/Palettes/Palettes.html @@ -32,4 +32,60 @@ #71808E
#A2A09F +

Bender

+ #49291A +
+ #9C9997 +
+ #7F6563 +
+ #81818D +
+ #9FA3A7 +
+ #95959B +

Great Green

+ #5E5546 +
+ #29281E +
+ #51574B +
+ #4D493A +
+ #3A3D33 +
+ #575042 +
+ #5E4F40 +
+ #453D2C +

Lochre

+ #B36C36 +
+ #853B22 +
+ #9E5A2B +
+ #CB7A38 +
+ #F7B285 +
+ #7D5E58 +
+ #C69583 +
+ #4C1E0C +

Red Haze

+ #6D4033 +
+ #B7A4A5 +
+ #93756D +
+ #431B10 +
+ #6B4746 +
+ #8E7C7C
\ No newline at end of file diff --git a/src/image_functions.rs b/src/image_functions.rs index 27088e6..07f6d66 100644 --- a/src/image_functions.rs +++ b/src/image_functions.rs @@ -10,13 +10,17 @@ use std::{ }; use crate::{ - structs::{ColorIndex, RichColor}, + structs::{ColorIndex, PaletteError, RichColor}, utilities::extract_name, Cli, }; /// Extract a subset of most representative colors -pub(crate) fn extract_kcluster(image: &PathBuf, cli: &Cli, pb: &ProgressBar) -> ColorIndex { +pub(crate) fn extract_kcluster( + image: &PathBuf, + cli: &Cli, + pb: &ProgressBar, +) -> Result { let name = extract_name(image); let runs = cli.runs.unwrap_or(8); let nb_colors = cli.nb_colors.unwrap_or(8); @@ -29,7 +33,7 @@ pub(crate) fn extract_kcluster(image: &PathBuf, cli: &Cli, pb: &ProgressBar) -> let mut rgb_pixels: Vec> = Vec::new(); // Open the image let img = image::open(image_path) - .expect("Couldn't open image") + .map_err(|e| PaletteError::ImageLoad(image.to_path_buf(), e))? .into_rgba8(); let img_vec: &[Srgba] = img.as_raw().components_as(); @@ -77,14 +81,19 @@ pub(crate) fn extract_kcluster(image: &PathBuf, cli: &Cli, pb: &ProgressBar) -> }) .collect::>(); - ColorIndex::new(name, colors) + Ok(ColorIndex::new(name, colors)) } /// Extract the first nb unique colors -pub(crate) fn extract_colors(image_path: &PathBuf, cli: &Cli, pb: &ProgressBar) -> ColorIndex { +pub(crate) fn extract_colors( + image_path: &PathBuf, + cli: &Cli, + pb: &ProgressBar, +) -> Result { let _ = cli; let name = extract_name(image_path); - let img = image::open(Path::new(&image_path)).expect("Failed to open image"); + let img = image::open(Path::new(&image_path)) + .map_err(|e| PaletteError::ImageLoad(image_path.to_path_buf(), e))?; // Create a HashSet to store unique colors let mut colors = HashSet::new(); @@ -129,10 +138,10 @@ pub(crate) fn extract_colors(image_path: &PathBuf, cli: &Cli, pb: &ProgressBar) // if cli.verbosity{ // println!("[{}] Found {} unique colors", name, colors.len()); // } - ColorIndex::new( + Ok(ColorIndex::new( name, vec.iter() .map(|(hue, rgb, luma)| RichColor::new(*hue, *luma, rgb.to_owned())) .collect(), - ) + )) } diff --git a/src/main.rs b/src/main.rs index 5f80dcc..ee280d9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,7 +10,7 @@ use std::{ path::PathBuf, time::{Duration, Instant}, }; -use structs::{ColorIndex, ExtractMode}; +use structs::{ColorIndex, ExtractMode, PaletteError}; use utilities::{export_html, small_name}; /// CLI for extracting a color palette from an image and exporting it. @@ -46,20 +46,18 @@ struct Cli { threads: Option, } -fn main() { +fn main() -> Result<(), PaletteError> { let started = Instant::now(); let spinner_style = ProgressStyle::with_template( "[{elapsed_precise}] {spinner} {bar:40.cyan/blue} {pos}/{len} [{prefix:.bold.dim}]", - ) - .unwrap() + )? .tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ "); let cli = Cli::parse(); if let Some(t) = cli.threads { rayon::ThreadPoolBuilder::new() .num_threads(t) - .build_global() - .unwrap(); + .build_global()?; } let export_path = match cli.export.clone() { Some(e) => e, @@ -100,11 +98,30 @@ fn main() { pb_general.inc(1); r }) + .filter_map(|x| match x { + Ok(c) => Some(c), + Err(e) => { + // match e { + // PaletteError::ImageLoad(e) => { + + // }, + // _ => (), + // } + pb_general.println(format!("[ERR] {}", e)); + None + } + }) .collect::>(); pb_general.finish_and_clear(); if cli.verbosity { println!("[INFO] Done in {}", HumanDuration(started.elapsed())); } - export_html(export_path, colorblobs); + // let r = export_html(export_path, colorblobs); + // match r { + // Ok(_) => (), + // Err(ref e) => println!("[Error] {}", e), + // } + // r + export_html(export_path, colorblobs) } diff --git a/src/structs.rs b/src/structs.rs index 4a0c919..05e15db 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -1,4 +1,10 @@ +use std::path::PathBuf; + use clap::ValueEnum; +use image::ImageError; +use indicatif::style::TemplateError; +use rayon::ThreadPoolBuildError; +use thiserror::Error; /// Supported export formats for the color palette #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] @@ -38,3 +44,18 @@ impl RichColor { Self { hue, luma, rgb } } } + +#[derive(Error, Debug)] +pub enum PaletteError { + #[error("image {:#?} couldn't be loaded ({:?})", .0, .1)] + ImageLoad(PathBuf, ImageError), + + #[error("an error occured when creating the progressbar")] + ProgressBar(#[from] TemplateError), + + #[error("an error occured when building the ThreadPool")] + ThreadPool(#[from] ThreadPoolBuildError), + + #[error("the data couldn't be written to file {:?}",.0)] + HTMLExport(#[from] std::io::Error), +} diff --git a/src/utilities.rs b/src/utilities.rs index 3f9452a..4cd7c84 100644 --- a/src/utilities.rs +++ b/src/utilities.rs @@ -5,7 +5,7 @@ use std::{ path::{Path, PathBuf}, }; -use crate::structs::ColorIndex; +use crate::structs::{ColorIndex, PaletteError}; /// Make a smaller name pub(crate) fn small_name(name: &Path) -> String { @@ -14,14 +14,14 @@ pub(crate) fn small_name(name: &Path) -> String { let (beg, end, file_name) = if l > 2 { ( ancs[l - 2].to_string_lossy(), - ancs[1].file_name().unwrap().to_string_lossy(), - ancs[0].file_name().unwrap().to_string_lossy(), + extract_full_name(ancs[1]), + extract_full_name(ancs[0]), ) } else { ( Cow::Borrowed(""), Cow::Borrowed(""), - ancs[0].file_name().unwrap().to_string_lossy(), + extract_full_name(ancs[0]), ) }; @@ -34,40 +34,35 @@ pub(crate) fn small_name(name: &Path) -> String { } } +/// Extract the full name of the last element, as string +fn extract_full_name(ancs: &Path) -> Cow<'_, str> { + ancs.file_name().unwrap_or_default().to_string_lossy() +} + /// Extract the image name pub(crate) fn extract_name(image: &Path) -> String { image .file_name() - .unwrap() + .unwrap_or_default() .to_string_lossy() .split(".") .next() - .unwrap() + .unwrap_or("") .to_string() } /// Export the file as html -pub(crate) fn export_html(export_path: PathBuf, color_vec: Vec) { - // let mut out = File::create(&export_path).expect("Can't open output file"); - let mut out = BufWriter::new(File::create(&export_path).expect("Can't open output file")); +pub(crate) fn export_html( + export_path: PathBuf, + color_vec: Vec, +) -> Result<(), PaletteError> { + let mut out = BufWriter::new(File::create(&export_path)?); write!( out, r#""# - ).unwrap(); - write!( - out, - "Palette: {}", - &export_path - .file_name() - .unwrap() - .to_str() - .unwrap() - .split(".") - .next() - .unwrap() - ) - .unwrap(); + )?; + write!(out, "Palette: {}", &extract_name(&export_path))?; write!( out, r#" "# - ) - .unwrap(); + )?; for blob in color_vec { - write!(out, "

{}

", blob.name).unwrap(); - write!(out, "
").unwrap(); + write!(out, "

{}

", blob.name)?; + write!(out, "
")?; for v in blob.colors { let c = if v.luma < 60 { "FFFFFF" } else { "000000" }; - write!(out,"
\n {} \n
",v.rgb_string(),c,v.rgb_string()).expect("Can't write color in the output"); + write!(out,"
\n {} \n
",v.rgb_string(),c,v.rgb_string())?; } - write!(out, "
").unwrap(); + write!(out, "
")?; } - write!(out, "").unwrap(); - println!( - "[INFO] Exported pallete to file: {}", - export_path.to_string_lossy() - ); + write!(out, "")?; + Ok(()) } // Save the kcluster picture