42 lines
1.6 KiB
Rust
42 lines
1.6 KiB
Rust
//! BMP raster decoding and the density recorded by the DIB header.
|
|
use image::{ColorType, ImageDecoder, codecs::bmp::BmpDecoder};
|
|
use std::io::Cursor;
|
|
|
|
use super::png::SampledImage;
|
|
|
|
pub(super) const SIGNATURE: &[u8] = b"BM";
|
|
|
|
pub(super) fn decode(bytes: &[u8]) -> Result<(SampledImage, [f64; 2]), String> {
|
|
let dib = bytes.get(14..).ok_or("truncated BMP file header")?;
|
|
let long = |at: usize| -> Result<u32, String> {
|
|
let word = dib.get(at..at + 4).ok_or("truncated BMP DIB header")?;
|
|
Ok(u32::from_le_bytes(word.try_into().unwrap()))
|
|
};
|
|
let density = match long(0)? {
|
|
12 => [72.0; 2],
|
|
40 | 52 | 56 | 108 | 124 => {
|
|
let ppm = [long(24)? as i32, long(28)? as i32];
|
|
if ppm.iter().all(|&value| value > 0) {
|
|
ppm.map(|value| f64::from(value) * 0.0254)
|
|
} else {
|
|
[72.0; 2]
|
|
}
|
|
}
|
|
_ => return Err("unsupported BMP DIB header".into()),
|
|
};
|
|
let decoder = BmpDecoder::new(Cursor::new(bytes)).map_err(|error| error.to_string())?;
|
|
if decoder.color_type() != ColorType::Rgb8 {
|
|
return Err("unsupported BMP color layout for XDV".into());
|
|
}
|
|
let (width, height) = decoder.dimensions();
|
|
let capacity = decoder.total_bytes();
|
|
if capacity > 256 * 1024 * 1024 {
|
|
return Err("decoded BMP exceeds native image capacity".into());
|
|
}
|
|
let mut samples = vec![0; capacity as usize];
|
|
decoder
|
|
.read_image(&mut samples)
|
|
.map_err(|error| error.to_string())?;
|
|
Ok((SampledImage::rgb8([width, height], samples), density))
|
|
}
|