pub const PNG_SIGNATURE: [u8; 8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PngHeader {
pub width: u32,
pub height: u32,
pub bit_depth: u8,
pub color_type: u8,
pub interlace_method: u8,
}
impl PngHeader {
pub fn has_alpha_channel(&self) -> bool {
self.color_type == 4 || self.color_type == 6
}
}
pub fn parse_ihdr(bytes: &[u8]) -> Option<PngHeader> {
if bytes.len() < 33 || bytes[0..8] != PNG_SIGNATURE {
return None;
}
if &bytes[12..16] != b"IHDR" {
return None;
}
let width = u32::from_be_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]);
let height = u32::from_be_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]);
Some(PngHeader {
width,
height,
bit_depth: bytes[24],
color_type: bytes[25],
interlace_method: bytes[28],
})
}
#[inline]
pub fn paeth_predictor(a: u8, b: u8, c: u8) -> u8 {
let a_i = a as i32;
let b_i = b as i32;
let c_i = c as i32;
let p = a_i + b_i - c_i;
let pa = (p - a_i).abs();
let pb = (p - b_i).abs();
let pc = (p - c_i).abs();
if pa <= pb && pa <= pc {
a
} else if pb <= pc {
b
} else {
c
}
}
pub fn sanitize_zero_alpha_rgba(rgba: &mut [u8]) -> usize {
let mut cleaned = 0usize;
for px in rgba.chunks_exact_mut(4) {
if px[3] == 0 && (px[0] != 0 || px[1] != 0 || px[2] != 0) {
px[0] = 0;
px[1] = 0;
px[2] = 0;
cleaned += 1;
}
}
cleaned
}