use clap::{Parser, ValueEnum}; use palette::{FromColor, Hsl, Srgb}; use std::fs::File; use std::io::Write; use std::path::PathBuf; use image::{GenericImageView, Pixel}; use std::collections::HashSet; use std::path::Path; /// CLI for extracting a color palette from an image and exporting it. #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Cli { /// Path of the image to extract the palette from #[arg(short, long, value_name = "IMAGE_PATH")] image: PathBuf, /// Path to export the palette to #[arg(short, long, value_name = "EXPORT_PATH")] export: Option, /// Format in which to export the palette (e.g., JSON, XML) #[arg(short, long, value_enum, value_name = "FORMAT")] format: Option, } /// Supported export formats for the color palette #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] enum PaletteFormat { HTML, Md, } fn main() { let cli = Cli::parse(); let export_path = match cli.export { Some(e) => e, None => cli.image.as_path().with_extension("html"), }; // Display parsed arguments println!("[INFO] Image Path: {:?}", &cli.image); println!("[INFO] Export Path: {:?}", &export_path); println!("[INFO] Export Format: {:?}", &cli.format); let image_path = cli.image; // Open the image let img = image::open(&Path::new(&image_path)).expect("Failed to open image"); // Create a HashSet to store unique colors let mut colors = HashSet::new(); // Iterate over the pixels for pixel in img.pixels() { // Get the color as a tuple (R, G, B, A) let rgb = pixel.2.to_rgb(); let srgb = Srgb::new( rgb[0] as f64 / 255., rgb[1] as f64 / 255., rgb[2] as f64 / 255., ); let hsl = Hsl::from_color(srgb); // Insert the color into the HashSet colors.insert(( rgb[0], rgb[1], rgb[2], (hsl.hue.into_positive_degrees() * 100.) as u32, )); } let mut vec = Vec::with_capacity(colors.len() + 1); // Print the unique colors for color in &colors { println!("Color: {:?}", color); vec.push(format!("#{:02X}{:02X}{:02X}", color.0, color.1, color.2)); } println!("Found {} unique colors", colors.len()); let mut out = File::create(&export_path).expect("Can't open output file"); write!( out, r#""# ).unwrap(); write!(out, "{:?}", &export_path.file_name()).unwrap(); write!( out, r#"
"# ) .unwrap(); for v in vec { write!(out,"
\n {} \n
",v,v).expect("Can't write color in the output"); } write!(out, "").unwrap(); }