mln-rs-engine 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
// The `png` crate decodes to straight RGBA8:
//
//   palette, gray < 8 bit, tRNS  -> expanded (Transformations::EXPAND)
//   16-bit channels              -> their high byte (Transformations::STRIP_16)
//   gray                         -> RGB, done below
//   no alpha                     -> opaque alpha, done below
//
// No gamma, sRGB or ICC profile conversion applies. Interlaced images are
// deinterlaced.

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.starts_with(&SIGNATURE) {
        return Err(Error::invalid_argument("invalid PNG: no PNG signature"));
    }

    let invalid = |e: png::DecodingError| Error::invalid_argument(format!("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("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_set_gray_to_rgb + png_set_add_alpha(0xff)
            png::ColorType::Grayscale => {
                for (s, d) in src.iter().zip(dst.as_chunks_mut::<4>().0) {
                    *d = [*s, *s, *s, 0xff];
                }
            }
            // png_set_gray_to_rgb
            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_set_add_alpha(0xff)
            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 => {
                // EXPAND always turns palette images into RGB(A).
                return Err(Error::invalid_argument("invalid PNG: unexpanded palette"));
            }
        }
    }
    debug_assert_eq!(image.data.len(), pixels * 4);

    Ok(premultiply(image))
}