mln-rs-engine 0.0.23

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::image::expand_to_rgba;
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 too_large = || Error::invalid_argument("invalid WebP: image too large");
    // RGBA, with opaque alpha for images without alpha: an RGB image decodes
    // to the front of the RGBA one, which then widens its pixels in place.
    let bytes = (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(4)).ok_or_else(too_large)?;
    let buffer_size = decoder.output_buffer_size().ok_or_else(too_large)?;
    let mut rgba = vec![0u8; bytes];
    decoder.read_image(&mut rgba[..buffer_size]).map_err(invalid)?;
    if !decoder.has_alpha() {
        expand_to_rgba(&mut rgba, |[r, g, b]| [r, g, b, 255]);
    }

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