use crate::{ImageBufferRef, PixelFormat, WatermarkError};
pub(crate) fn validate_image(image: ImageBufferRef<'_>) -> Result<(), WatermarkError> {
if image.width == 0 || image.height == 0 {
return Err(WatermarkError::InvalidImageDimensions(
"width and height must be greater than zero".to_string(),
));
}
let channels = image.pixel_format.channels();
let width = usize::try_from(image.width).map_err(|_| {
WatermarkError::InvalidImageDimensions("width does not fit in usize".to_string())
})?;
let height = usize::try_from(image.height).map_err(|_| {
WatermarkError::InvalidImageDimensions("height does not fit in usize".to_string())
})?;
let min_stride = width.checked_mul(channels).ok_or_else(|| {
WatermarkError::InvalidImageDimensions("width * channels overflows".to_string())
})?;
if image.stride < min_stride {
return Err(WatermarkError::InvalidImageDimensions(
"stride is smaller than width * bytes_per_pixel".to_string(),
));
}
let required_len = if height == 0 {
0
} else {
image
.stride
.checked_mul(height - 1)
.and_then(|offset| offset.checked_add(min_stride))
.ok_or_else(|| {
WatermarkError::InvalidImageDimensions("image buffer length overflows".to_string())
})?
};
if image.data.len() < required_len {
return Err(WatermarkError::InvalidImageDimensions(
"data length is shorter than stride and dimensions require".to_string(),
));
}
Ok(())
}
pub(crate) fn luma(pixel: &[u8], format: PixelFormat) -> f32 {
debug_assert!(pixel.len() >= format.channels());
0.299 * pixel[0] as f32 + 0.587 * pixel[1] as f32 + 0.114 * pixel[2] as f32
}
pub(crate) fn add_luma_delta(pixel: &mut [u8], format: PixelFormat, delta: f32) {
debug_assert!(pixel.len() >= format.channels());
let channels = format.channels().min(3);
for channel in pixel.iter_mut().take(channels) {
let value = (*channel as f32 + delta).round().clamp(0.0, 255.0);
*channel = value as u8;
}
}