use mln_style::bitmap::{PremultipliedImage, UnassociatedImage};
use mln_style::error::Error;
use mln_style::size::Size;
use crate::image::premultiply::premultiply;
pub fn decode_png(data: &[u8]) -> Result<PremultipliedImage, Error> {
const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n'];
if data.len() < 8 {
return Err(Error::invalid_argument("PNG reader: Could not read image"));
}
if data[..8] != SIGNATURE {
return Err(Error::invalid_argument("File or stream is not a png"));
}
let invalid = |e: png::DecodingError| Error::invalid_argument(format!("failed to read invalid png: '{e}'"));
let mut decoder = png::Decoder::new(std::io::Cursor::new(data));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder.read_info().map_err(invalid)?;
let (width, height) = {
let info = reader.info();
(info.width, info.height)
};
let buffer_size = reader
.output_buffer_size()
.ok_or_else(|| Error::invalid_argument("failed to read invalid png: 'image too large'"))?;
let mut buffer = vec![0u8; buffer_size];
let output = reader.next_frame(&mut buffer).map_err(invalid)?;
debug_assert_eq!(output.bit_depth, png::BitDepth::Eight);
let mut image = UnassociatedImage::new(Size::new(width, height));
let pixels = width as usize * height as usize;
let rows = buffer.chunks(output.line_size).take(height as usize);
let dst_rows = image.data.chunks_exact_mut(width as usize * 4);
for (src, dst) in rows.zip(dst_rows) {
match output.color_type {
png::ColorType::Grayscale => {
for (s, d) in src.iter().zip(dst.as_chunks_mut::<4>().0) {
*d = [*s, *s, *s, 0xff];
}
}
png::ColorType::GrayscaleAlpha => {
for (s, d) in src.as_chunks::<2>().0.iter().zip(dst.as_chunks_mut::<4>().0) {
*d = [s[0], s[0], s[0], s[1]];
}
}
png::ColorType::Rgb => {
for (s, d) in src.as_chunks::<3>().0.iter().zip(dst.as_chunks_mut::<4>().0) {
*d = [s[0], s[1], s[2], 0xff];
}
}
png::ColorType::Rgba => {
dst.copy_from_slice(&src[..dst.len()]);
}
png::ColorType::Indexed => {
return Err(Error::invalid_argument("failed to read invalid png: 'unexpanded palette'"));
}
}
}
debug_assert_eq!(image.data.len(), pixels * 4);
Ok(premultiply(image))
}