use std::io::Read;
use crate::error::WsiError;
use crate::tile::Photometric;
use image::{DynamicImage, ImageBuffer, RgbImage};
use jpeg_decoder::Decoder;
use jpeg_decoder::PixelFormat;
#[derive(Debug, Clone, PartialEq)]
pub struct JpegDecoder;
impl JpegDecoder {
pub fn decode<R: Read>(
reader: R,
color_transform: &Photometric,
) -> Result<DynamicImage, WsiError> {
let mut decoder = Decoder::new(reader);
decoder.set_color_transform(color_transform.jpeg_color_transform());
let pixels = decoder.decode().map_err(|_| WsiError::UnsupportedFormat)?;
let info = decoder.info().ok_or(WsiError::InvalidMetadata)?;
match info.pixel_format {
PixelFormat::RGB24 => {
let image: RgbImage =
ImageBuffer::from_raw(info.width.into(), info.height.into(), pixels)
.ok_or(WsiError::InvalidMetadata)?;
Ok(DynamicImage::ImageRgb8(image))
}
PixelFormat::L8 => {
let image =
image::GrayImage::from_raw(info.width.into(), info.height.into(), pixels)
.ok_or(WsiError::InvalidMetadata)?;
Ok(DynamicImage::ImageLuma8(image))
}
_ => Err(WsiError::UnsupportedFormat),
}
}
}