about summary refs log tree commit diff
path: root/squash/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'squash/src/main.rs')
-rw-r--r--squash/src/main.rs55
1 files changed, 41 insertions, 14 deletions
diff --git a/squash/src/main.rs b/squash/src/main.rs
index da3cfbf..fe7f310 100644
--- a/squash/src/main.rs
+++ b/squash/src/main.rs
@@ -3,6 +3,7 @@ use std::{fs::File, io::BufWriter};
 use anyhow::{anyhow, bail};
 use camino::{Utf8Path, Utf8PathBuf};
 use colorsquash::Squasher;
+use gifed::writer::{GifBuilder, ImageBuilder};
 use png::{ColorType, Decoder, Encoder};
 use zune_jpeg::{zune_core::colorspace::ColorSpace, JpegDecoder};
 
@@ -60,17 +61,24 @@ fn main() -> Result<(), anyhow::Error> {
 		color_count
 	);
 
-	// PNG Output
-	let file = File::create(output_path)?;
-	let bufw = BufWriter::new(file);
-
-	let mut enc = Encoder::new(bufw, image.width as u32, image.height as u32);
-	enc.set_color(ColorType::Indexed);
-	enc.set_depth(png::BitDepth::Eight);
-	enc.set_palette(squasher.palette_bytes());
-	enc.write_header()?.write_image_data(&image.data)?;
+	match output_path.extension() {
+		None => {
+			eprintln!("can't determine output filetype! defaulting to png");
+			save_png(image, squasher, output_path)
+		}
+		Some("png") => save_png(image, squasher, output_path),
+		Some("gif") => save_gif(image, squasher, output_path),
+		Some(ext) => {
+			eprintln!("unknown filetype '{ext}'!\nSupport output types are: GIF, PNG");
+			std::process::exit(1);
+		}
+	}
+}
 
-	Ok(())
+struct Image {
+	width: usize,
+	height: usize,
+	data: Vec<u8>,
 }
 
 fn get_png<P: AsRef<Utf8Path>>(path: P) -> Result<Image, anyhow::Error> {
@@ -124,8 +132,27 @@ fn get_jpg<P: AsRef<Utf8Path>>(path: P) -> Result<Image, anyhow::Error> {
 	})
 }
 
-struct Image {
-	width: usize,
-	height: usize,
-	data: Vec<u8>,
+fn save_png(image: Image, squasher: Squasher<u8>, path: Utf8PathBuf) -> Result<(), anyhow::Error> {
+	let file = File::create(path)?;
+	let bufw = BufWriter::new(file);
+
+	let mut enc = Encoder::new(bufw, image.width as u32, image.height as u32);
+	enc.set_color(ColorType::Indexed);
+	enc.set_depth(png::BitDepth::Eight);
+	enc.set_palette(squasher.palette_bytes());
+	enc.write_header()?.write_image_data(&image.data)?;
+
+	Ok(())
+}
+
+fn save_gif(image: Image, squasher: Squasher<u8>, path: Utf8PathBuf) -> Result<(), anyhow::Error> {
+	// I don't think I like this API anymore. It's a builder API, that's fine.
+	// I should make it so you can mutate the Gif directly.
+	GifBuilder::new(image.width as u16, image.height as u16)
+		.palette(squasher.palette_bytes().as_slice().try_into().unwrap())
+		.image(ImageBuilder::new(image.width as u16, image.height as u16).build(image.data)?)
+		.build()?
+		.save(path)?;
+
+	Ok(())
 }