2021-05-17 16:40:58 +01:00
|
|
|
use std::path::PathBuf;
|
2021-05-15 16:59:51 +01:00
|
|
|
use serde_derive::{Serialize, Deserialize};
|
2021-05-17 16:40:58 +01:00
|
|
|
use std::fs::read_to_string;
|
2021-11-14 18:02:13 +00:00
|
|
|
use image::{DynamicImage, ImageBuffer};
|
|
|
|
|
use crate::Palette;
|
2021-05-15 16:59:51 +01:00
|
|
|
|
2022-03-12 18:13:03 +00:00
|
|
|
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
2021-05-15 16:59:51 +01:00
|
|
|
pub struct Image {
|
|
|
|
|
pub name: String,
|
2021-05-18 21:11:51 +01:00
|
|
|
/// colour indices - todo convert to [u8; 64]?
|
2021-05-15 16:59:51 +01:00
|
|
|
pub pixels: Vec<u8>,
|
|
|
|
|
}
|
|
|
|
|
|
2021-05-17 16:40:58 +01:00
|
|
|
impl Image {
|
|
|
|
|
pub fn from_file(path: PathBuf) -> Self {
|
|
|
|
|
let name = path.file_stem().unwrap().to_str().unwrap().into();
|
|
|
|
|
let mut pixels: Vec<u8> = Vec::new();
|
2021-05-15 16:59:51 +01:00
|
|
|
|
2021-05-18 20:17:12 +01:00
|
|
|
// todo .matches [0..3] instead of replacing whitespace?
|
|
|
|
|
for char in read_to_string(&path).unwrap().replace('\n', "").chars() {
|
|
|
|
|
pixels.push(char.to_string().parse().unwrap());
|
2021-05-17 16:40:58 +01:00
|
|
|
}
|
2021-05-15 16:59:51 +01:00
|
|
|
|
2021-05-17 16:40:58 +01:00
|
|
|
Self { name, pixels }
|
|
|
|
|
}
|
2021-11-14 18:02:13 +00:00
|
|
|
|
2022-03-12 18:13:03 +00:00
|
|
|
pub fn into_image(self, palette: &Palette) -> DynamicImage {
|
2021-11-14 18:02:13 +00:00
|
|
|
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())
|
|
|
|
|
}
|
2021-05-15 16:59:51 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
|
mod test {
|
2021-05-17 16:40:58 +01:00
|
|
|
use std::path::PathBuf;
|
|
|
|
|
use crate::image::Image;
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn image_from_text() {
|
|
|
|
|
let path = PathBuf::from("src/test-resources/basic/images/avatar.txt");
|
|
|
|
|
let output = Image::from_file(path);
|
|
|
|
|
let expected = crate::mock::image::avatar();
|
|
|
|
|
assert_eq!(output, expected);
|
|
|
|
|
}
|
2021-11-14 18:02:13 +00:00
|
|
|
|
|
|
|
|
#[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);
|
|
|
|
|
}
|
2021-05-15 16:59:51 +01:00
|
|
|
}
|