use std::time::{Duration, Instant};
use image::{DynamicImage, ImageFormat};
use std::path::Path;
pub trait Drawable {
fn draw(&self, image: &mut DynamicImage);
}
pub struct ImageWrapper {
image: DynamicImage,
}
impl ImageWrapper {
pub fn new(image: DynamicImage) -> Self {
ImageWrapper { image }
}
pub fn draw<T: Drawable>(&mut self, drawable: &T) {
drawable.draw(&mut self.image);
}
pub fn get_image(&self) -> &DynamicImage {
&self.image
}
pub fn save_image(&self, output_path: &str) -> Result<Duration, Box<dyn std::error::Error>> {
let start = Instant::now();
let path = Path::new(output_path);
let extension = path.extension()
.and_then(|ext| ext.to_str())
.map(|ext| ext.to_lowercase());
match extension.as_deref() {
Some("jpg") | Some("jpeg") => {
let rgb_image = match &self.image {
DynamicImage::ImageRgba8(rgba_img) => {
DynamicImage::ImageRgb8(
image::ImageBuffer::from_fn(
rgba_img.width(),
rgba_img.height(),
|x, y| {
let rgba_pixel = rgba_img.get_pixel(x, y);
image::Rgb([rgba_pixel[0], rgba_pixel[1], rgba_pixel[2]])
}
)
)
}
_ => self.image.clone(), };
rgb_image.save_with_format(output_path, ImageFormat::Jpeg)?;
}
Some("png") => {
self.image.save_with_format(output_path, ImageFormat::Png)?;
}
Some("bmp") => {
self.image.save_with_format(output_path, ImageFormat::Bmp)?;
}
Some("gif") => {
self.image.save_with_format(output_path, ImageFormat::Gif)?;
}
Some("tiff") | Some("tif") => {
self.image.save_with_format(output_path, ImageFormat::Tiff)?;
}
_ => {
self.image.save(output_path)?;
}
}
Ok(start.elapsed())
}
pub fn save_image_as_rgb(&self, output_path: &str) -> Result<Duration, Box<dyn std::error::Error>> {
let start = Instant::now();
let rgb_image = self.image.to_rgb8();
let dynamic_rgb = DynamicImage::ImageRgb8(rgb_image);
dynamic_rgb.save(output_path)?;
Ok(start.elapsed())
}
pub fn save_with_format(&self, output_path: &str, format: ImageFormat) -> Result<Duration, Box<dyn std::error::Error>> {
let start = Instant::now();
match format {
ImageFormat::Jpeg => {
let rgb_image = self.image.to_rgb8();
let dynamic_rgb = DynamicImage::ImageRgb8(rgb_image);
dynamic_rgb.save_with_format(output_path, format)?;
}
_ => {
self.image.save_with_format(output_path, format)?;
}
}
Ok(start.elapsed())
}
}