Image to DynamicImage (and test)

This commit is contained in:
Max Bradbury 2021-11-14 18:02:13 +00:00
parent 82c0f78177
commit 1532700ea5
1 changed files with 24 additions and 0 deletions

View File

@ -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<u8> = 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);
}
}