use std::path::Path;
use gamut::core::{DecodeImage, Dimensions, ImageBuf, Rgb8, Rgba8};
use gamut::webp::WebpDecoder;
use crate::error::CliError;
pub(crate) fn decode_rgb8(path: &Path) -> Result<(Vec<u8>, Dimensions), CliError> {
decode(path, false)
}
pub(crate) fn decode_rgba8(path: &Path) -> Result<(Vec<u8>, Dimensions), CliError> {
decode(path, true)
}
fn decode(path: &Path, want_alpha: bool) -> Result<(Vec<u8>, Dimensions), CliError> {
let bytes = std::fs::read(path).map_err(|source| CliError::Io {
path: path.to_path_buf(),
source,
})?;
decode_bytes(path, &bytes, want_alpha)
}
fn decode_bytes(
path: &Path,
bytes: &[u8],
want_alpha: bool,
) -> Result<(Vec<u8>, Dimensions), CliError> {
if is_webp(bytes) {
let decoder = WebpDecoder::new();
return Ok(if want_alpha {
let img: ImageBuf<Rgba8> = decoder.decode_image(bytes)?;
let dims = img.dimensions();
(img.into_samples(), dims)
} else {
let img: ImageBuf<Rgb8> = decoder.decode_image(bytes)?;
let dims = img.dimensions();
(img.into_samples(), dims)
});
}
let decoded = image::load_from_memory(bytes).map_err(|source| CliError::Decode {
path: path.to_path_buf(),
source,
})?;
let (buf, width, height) = if want_alpha {
let rgba = decoded.to_rgba8();
let (w, h) = rgba.dimensions();
(rgba.into_raw(), w, h)
} else {
let rgb = decoded.to_rgb8();
let (w, h) = rgb.dimensions();
(rgb.into_raw(), w, h)
};
Ok((buf, Dimensions { width, height }))
}
fn is_webp(bytes: &[u8]) -> bool {
bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP"
}
#[cfg(test)]
mod tests {
use super::*;
use gamut::core::{EncodeImage, ImageRef};
use gamut::webp::WebpEncoder;
fn lossless_webp(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
WebpEncoder::lossless()
.encode_image(
ImageRef::<Rgba8>::new(rgba, Dimensions { width, height }).unwrap(),
&mut out,
)
.expect("encode webp");
out
}
#[test]
fn sniffs_and_decodes_opaque_webp_to_rgb8() {
let rgba = [
0x10, 0x20, 0x30, 0xff, 0x40, 0x50, 0x60, 0xff, 0x70, 0x80, 0x90, 0xff, 0xa0, 0xb0, 0xc0, 0xff, ];
let webp = lossless_webp(2, 2, &rgba);
assert!(is_webp(&webp));
let (rgb, dims) = decode_bytes(Path::new("mem.webp"), &webp, false).unwrap();
assert_eq!(
dims,
Dimensions {
width: 2,
height: 2
}
);
assert_eq!(
rgb,
[
0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0, 0xb0, 0xc0
]
);
}
#[test]
fn decodes_transparent_webp_to_rgba8() {
#[rustfmt::skip]
let rgba = [
0x11, 0x22, 0x33, 0x00,
0x44, 0x55, 0x66, 0x80,
0x77, 0x88, 0x99, 0xc0,
0xaa, 0xbb, 0xcc, 0xff,
];
let webp = lossless_webp(2, 2, &rgba);
let (out, dims) = decode_bytes(Path::new("mem.webp"), &webp, true).unwrap();
assert_eq!(
dims,
Dimensions {
width: 2,
height: 2
}
);
assert_eq!(out, rgba);
}
#[test]
fn non_riff_bytes_take_the_image_path() {
let junk = [0u8; 32];
assert!(!is_webp(&junk));
let err = decode_bytes(Path::new("junk.bin"), &junk, false).unwrap_err();
assert!(matches!(err, CliError::Decode { .. }));
}
}