From 1532700ea59cb079b9a2718147ba0480bc3d32b6 Mon Sep 17 00:00:00 2001 From: Max Bradbury Date: Sun, 14 Nov 2021 18:02:13 +0000 Subject: [PATCH] Image to DynamicImage (and test) --- src/image.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/image.rs b/src/image.rs index 571a8b3..3850c3d 100644 --- a/src/image.rs +++ b/src/image.rs @@ -1,6 +1,8 @@ use std::path::PathBuf; use serde_derive::{Serialize, Deserialize}; use std::fs::read_to_string; +use image::{DynamicImage, ImageBuffer}; +use crate::Palette; #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct Image { @@ -21,6 +23,16 @@ impl Image { Self { name, pixels } } + + fn into_image(self, palette: &Palette) -> DynamicImage { + let mut buffer: Vec = Vec::new(); + + for pixel in self.pixels { + buffer.append(&mut palette.get_colour_rgba8(&pixel)); + } + + DynamicImage::ImageRgba8(ImageBuffer::from_raw(8, 8, buffer).unwrap()) + } } #[cfg(test)] @@ -35,4 +47,16 @@ mod test { let expected = crate::mock::image::avatar(); assert_eq!(output, expected); } + + #[test] + fn image_to_dynamic_image() { + let palette = &crate::mock::palette::default(); + let output = crate::mock::image::avatar().into_image(palette); + + let expected = image::io::Reader::open( + "src/test-resources/images/avatar.png" + ).unwrap().decode().unwrap(); + + assert_eq!(output, expected); + } }