use crate::{Image, Margin, Result};
use image::flat::View;
use image::{GenericImageView, Rgba};
pub fn identify_transparency(image: Image) -> Result<Option<Margin>> {
let image: View<_, Rgba<u8>> = image.as_view()?;
let (width, height) = image.dimensions();
let half_width = width / 2;
let half_height = height / 2;
let transparency_end: u8 = 0xff - (0xff / 4);
let mut margin = Margin::zero();
for y in 0..half_height {
let Rgba([_, _, _, a]) = image.get_pixel(half_width, y);
if a > transparency_end {
margin.top = y as u16;
break;
}
}
for y in (half_height..height).rev() {
let Rgba([_, _, _, a]) = image.get_pixel(half_width, y);
if a > transparency_end {
margin.bottom = (height - y - 1) as u16;
break;
}
}
for x in 0..half_width {
let Rgba([_, _, _, a]) = image.get_pixel(x, half_height);
if a > transparency_end {
margin.left = x as u16;
break;
}
}
for x in (half_width..width).rev() {
let Rgba([_, _, _, a]) = image.get_pixel(x, half_height);
if a > transparency_end {
margin.right = (width - x - 1) as u16;
break;
}
}
Ok(Some(margin))
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn should_identify_macos_right_side_issue() -> Result<()> {
let image_org = image::open("tests/frames/frame-macos-right-side-issue.tga")?;
let image = image_org.into_rgba8();
let (width, height) = image.dimensions();
let Rgba([blue, green, red, alpha]) = image.get_pixel(width - 1, height / 2);
assert_eq!(alpha, &0, "the test image was not transparent");
assert_eq!(red, &0, "the test image is not as expected");
assert_eq!(green, &0, "the test image is not as expected");
assert_eq!(blue, &0, "the test image is not as expected");
let image_raw = image.into_flat_samples();
let margin = identify_transparency(image_raw)?;
assert_eq!(margin, Some(Margin::new(0, 14, 0, 0)));
Ok(())
}
}