2023-03-10 09:18:03 +11:00
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use std::sync::Arc;
|
|
|
|
|
|
|
|
use vello::peniko::{Blob, Format, Image};
|
|
|
|
|
|
|
|
/// Simple hack to support loading images for examples.
|
|
|
|
#[derive(Default)]
|
|
|
|
pub struct ImageCache {
|
|
|
|
files: HashMap<PathBuf, Image>,
|
|
|
|
bytes: HashMap<usize, Image>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ImageCache {
|
|
|
|
pub fn new() -> Self {
|
|
|
|
Self::default()
|
|
|
|
}
|
|
|
|
|
2023-03-11 07:14:34 +11:00
|
|
|
pub fn from_file(&mut self, path: impl AsRef<Path>) -> anyhow::Result<Image> {
|
2023-03-10 09:18:03 +11:00
|
|
|
let path = path.as_ref();
|
|
|
|
if let Some(image) = self.files.get(path) {
|
2023-03-11 07:14:34 +11:00
|
|
|
Ok(image.clone())
|
2023-03-10 09:18:03 +11:00
|
|
|
} else {
|
2023-03-11 07:14:34 +11:00
|
|
|
let data = std::fs::read(path)?;
|
2023-03-10 09:18:03 +11:00
|
|
|
let image = decode_image(&data)?;
|
|
|
|
self.files.insert(path.to_owned(), image.clone());
|
2023-03-11 07:14:34 +11:00
|
|
|
Ok(image)
|
2023-03-10 09:18:03 +11:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-11 07:14:34 +11:00
|
|
|
pub fn from_bytes(&mut self, key: usize, bytes: &[u8]) -> anyhow::Result<Image> {
|
2023-03-10 09:18:03 +11:00
|
|
|
if let Some(image) = self.bytes.get(&key) {
|
2023-03-11 07:14:34 +11:00
|
|
|
Ok(image.clone())
|
2023-03-10 09:18:03 +11:00
|
|
|
} else {
|
|
|
|
let image = decode_image(bytes)?;
|
|
|
|
self.bytes.insert(key, image.clone());
|
2023-03-11 07:14:34 +11:00
|
|
|
Ok(image)
|
2023-03-10 09:18:03 +11:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-11 07:14:34 +11:00
|
|
|
fn decode_image(data: &[u8]) -> anyhow::Result<Image> {
|
2023-03-10 09:18:03 +11:00
|
|
|
let image = image::io::Reader::new(std::io::Cursor::new(data))
|
2023-03-11 07:14:34 +11:00
|
|
|
.with_guessed_format()?
|
|
|
|
.decode()?;
|
2023-03-10 09:18:03 +11:00
|
|
|
let width = image.width();
|
|
|
|
let height = image.height();
|
|
|
|
let data = Arc::new(image.into_rgba8().into_vec());
|
|
|
|
let blob = Blob::new(data);
|
2023-03-11 07:14:34 +11:00
|
|
|
Ok(Image::new(blob, Format::Rgba8, width, height))
|
2023-03-10 09:18:03 +11:00
|
|
|
}
|