use std::{
borrow::Cow,
io::{Read, Seek},
};
use crate::{error::Result, item::RelationKind, structure::Structure};
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Thumbnail {
pub data: Vec<u8>,
media_type: Option<Cow<'static, str>>,
pub width: Option<u32>,
pub height: Option<u32>,
}
impl Thumbnail {
pub fn new(data: Vec<u8>) -> Self {
Self {
data,
media_type: None,
width: None,
height: None,
}
}
pub fn with_media_type(mut self, media_type: impl Into<Cow<'static, str>>) -> Self {
self.media_type = Some(media_type.into());
self
}
pub fn with_dimensions(mut self, width: u32, height: u32) -> Self {
self.width = Some(width);
self.height = Some(height);
self
}
pub fn media_type(&self) -> Option<&str> {
self.media_type.as_deref()
}
}
impl Structure {
pub fn embedded_thumbnail<R: Read + Seek>(&self, src: &mut R) -> Result<Option<Thumbnail>> {
let thumb = self.items().find(|e| {
e.relations()
.iter()
.any(|r| r.kind() == RelationKind::Thumbnail)
});
if let Some(e) = thumb {
let mut t = Thumbnail::new(self.read_item(src, e)?);
if let Some(m) = e.media_type() {
t = t.with_media_type(m.to_owned());
}
return Ok(Some(t));
}
#[cfg(feature = "exif")]
{
self.exif_thumbnail(src)
}
#[cfg(not(feature = "exif"))]
{
Ok(None)
}
}
}