use crate::{
conversion::{
converters::generic_converter::Imgii2dImage,
image_data::{ImageData, InternalImage},
},
error::ImgiiError,
};
use rayon::prelude::*;
#[derive(Debug, Clone)]
pub(crate) struct AsciiImageWriter {
pub(crate) imagebuf: ImageData,
}
impl From<ImageData> for AsciiImageWriter {
fn from(the_image: ImageData) -> Self {
Self {
imagebuf: the_image,
}
}
}
impl AsciiImageWriter {
pub(crate) fn from_2d_vec(the_image: Imgii2dImage) -> Result<Self, ImgiiError> {
if the_image.image_2d.is_empty() {
return Err(ImgiiError::InvalidArgument);
}
let char_width = the_image.image_2d[0].as_buffer().width();
let char_height = the_image.image_2d[0].as_buffer().height();
let height = char_height * the_image.height as u32;
let width = char_width * the_image.width as u32;
let mut canvas: InternalImage = image::ImageBuffer::new(width, height);
canvas.par_enumerate_pixels_mut().for_each(|(x, y, pixel)| {
let row = y / char_height;
let column = x / char_width;
let inner_x = x % char_width;
let inner_y = y % char_height;
let new_pixel = the_image.image_2d[column as usize + row as usize * the_image.width]
.as_buffer()
.get_pixel(inner_x, inner_y);
*pixel = *new_pixel;
});
Ok(Self {
imagebuf: ImageData::new(canvas),
})
}
}