use image::{DynamicImage, GenericImageView, Rgba, RgbaImage};
use log::info;
use std::path::Path;
use crate::tiff::errors::{TiffError, TiffResult};
pub fn apply_shape_mask(image: &DynamicImage, shape: &str) -> DynamicImage {
if shape.to_lowercase() != "circle" {
return image.clone();
}
let width = image.width();
let height = image.height();
let mut rgba = RgbaImage::new(width, height);
let center_x = width as f32 / 2.0;
let center_y = height as f32 / 2.0;
let radius = (width.min(height) / 2) as f32;
let rgb = image.to_rgb8();
for y in 0..height {
for x in 0..width {
let dx = x as f32 - center_x;
let dy = y as f32 - center_y;
let distance_squared = dx * dx + dy * dy;
if distance_squared <= radius * radius {
let pixel = rgb.get_pixel(x, y);
rgba.put_pixel(x, y, Rgba([pixel[0], pixel[1], pixel[2], 255]));
} else {
rgba.put_pixel(x, y, Rgba([0, 0, 0, 0]));
}
}
}
DynamicImage::ImageRgba8(rgba)
}
pub fn ensure_png_extension(file_path: &str) -> String {
let path = Path::new(file_path);
if let Some(ext) = path.extension() {
if ext.to_string_lossy().to_lowercase() == "png" {
return file_path.to_string();
}
}
let stem = path.file_stem().unwrap_or_default();
let parent = path.parent().unwrap_or_else(|| Path::new(""));
let new_path = parent.join(format!("{}.png", stem.to_string_lossy()));
new_path.to_string_lossy().to_string()
}
pub fn save_shaped_image(image: &DynamicImage, output_path: &str, shape: &str) -> TiffResult<()> {
let final_path = if shape.to_lowercase() == "circle" {
let png_path = ensure_png_extension(output_path);
if png_path != output_path {
info!("Changed output extension to PNG for transparency support: {}", png_path);
}
png_path
} else {
output_path.to_string()
};
match image.save(&final_path) {
Ok(_) => Ok(()),
Err(e) => Err(TiffError::GenericError(format!("Failed to save image: {}", e)))
}
}