#![deny(missing_docs)]
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
pub struct ReadmeDoctests;
use std::error::Error;
use std::fmt;
use frus_core::ImageData;
#[derive(Debug)]
pub struct DecodeError(String);
impl DecodeError {
pub fn message(&self) -> &str {
&self.0
}
}
impl fmt::Display for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "image decoding failed: {}", self.0)
}
}
impl Error for DecodeError {}
pub fn decode(bytes: &[u8]) -> Result<ImageData, DecodeError> {
let decoded = image::load_from_memory(bytes).map_err(|e| DecodeError(e.to_string()))?;
let rgba = decoded.to_rgba8();
let (width, height) = rgba.dimensions();
Ok(ImageData::from_rgba(width, height, rgba.into_raw()))
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
fn encode(img: &image::RgbaImage, format: image::ImageFormat) -> Vec<u8> {
let mut bytes = Vec::new();
image::DynamicImage::ImageRgba8(img.clone())
.write_to(&mut Cursor::new(&mut bytes), format)
.expect("encoding");
bytes
}
fn sample() -> image::RgbaImage {
let mut img = image::RgbaImage::from_pixel(4, 3, image::Rgba([0, 0, 0, 255]));
img.put_pixel(0, 0, image::Rgba([255, 0, 0, 255]));
img.put_pixel(3, 2, image::Rgba([0, 255, 0, 255]));
img
}
#[test]
fn png_round_trips_pixels_exactly() {
let png = encode(&sample(), image::ImageFormat::Png);
let data = decode(&png).expect("PNG decoding");
assert_eq!((data.width(), data.height()), (4, 3));
let rgba = data.rgba();
assert_eq!(&rgba[0..4], &[255, 0, 0, 255]);
let last = ((2 * 4 + 3) * 4) as usize;
assert_eq!(&rgba[last..last + 4], &[0, 255, 0, 255]);
}
#[test]
fn jpeg_decodes_with_correct_dimensions() {
let jpeg = encode(&sample(), image::ImageFormat::Jpeg);
let data = decode(&jpeg).expect("JPEG decoding");
assert_eq!((data.width(), data.height()), (4, 3));
assert_eq!(data.rgba().len(), 4 * 3 * 4);
}
#[test]
fn format_is_detected_from_magic_bytes() {
let png = encode(&sample(), image::ImageFormat::Png);
assert!(png.starts_with(&[0x89, 0x50, 0x4E, 0x47]), "PNG header");
assert!(decode(&png).is_ok());
}
#[test]
fn garbage_bytes_error_cleanly() {
let err = decode(b"not an image at all").unwrap_err();
assert!(!err.message().is_empty());
}
}