mln-rs-engine 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
// The `image-webp` crate decodes. Lossy (VP8) images use its bilinear
// ("fancy") chroma upsampling.

use std::io::Cursor;

use mln_style::bitmap::{PremultipliedImage, UnassociatedImage};
use mln_style::error::Error;
use mln_style::size::Size;

use crate::image::premultiply::premultiply;

pub(crate) fn decode_webp(data: &[u8]) -> Result<PremultipliedImage, Error> {
    let invalid = |e: image_webp::DecodingError| Error::invalid_argument(format!("invalid WebP: {e}"));
    let mut decoder = image_webp::WebPDecoder::new(Cursor::new(data)).map_err(invalid)?;

    let (width, height) = decoder.dimensions();
    let buffer_size =
        decoder.output_buffer_size().ok_or_else(|| Error::invalid_argument("invalid WebP: image too large"))?;
    let mut buffer = vec![0u8; buffer_size];
    decoder.read_image(&mut buffer).map_err(invalid)?;

    // RGBA, with opaque alpha for images without alpha.
    let rgba = if decoder.has_alpha() {
        buffer
    } else {
        let mut rgba = Vec::with_capacity(width as usize * height as usize * 4);
        for rgb in buffer.as_chunks::<3>().0 {
            rgba.extend_from_slice(&[rgb[0], rgb[1], rgb[2], 255]);
        }
        rgba
    };

    Ok(premultiply(UnassociatedImage::from_vec(Size::new(width, height), rgba)))
}