From ab236376a3f8f1ac3cdd8aeb0ffeee45e3de37e3 Mon Sep 17 00:00:00 2001 From: Cory Forsstrom Date: Thu, 6 Feb 2025 13:54:45 -0800 Subject: Add blurhash to gallery --- examples/gallery/src/civitai.rs | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) (limited to 'examples/gallery/src/civitai.rs') diff --git a/examples/gallery/src/civitai.rs b/examples/gallery/src/civitai.rs index 986b6bf2..c394ef1d 100644 --- a/examples/gallery/src/civitai.rs +++ b/examples/gallery/src/civitai.rs @@ -10,6 +10,7 @@ use std::sync::Arc; pub struct Image { pub id: Id, url: String, + hash: String, } impl Image { @@ -40,20 +41,37 @@ impl Image { Ok(response.items) } + pub async fn blurhash( + self, + width: u32, + height: u32, + ) -> Result { + task::spawn_blocking(move || { + let pixels = blurhash::decode(&self.hash, width, height, 1.0)?; + + Ok::<_, Error>(Rgba { + width, + height, + pixels: Bytes::from(pixels), + }) + }) + .await? + } + pub async fn download(self, size: Size) -> Result { let client = reqwest::Client::new(); let bytes = client .get(match size { Size::Original => self.url, - Size::Thumbnail => self + Size::Thumbnail { width } => self .url .split("/") .map(|part| { if part.starts_with("width=") { - "width=640" + format!("width={width}") } else { - part + part.to_string() } }) .collect::>() @@ -107,7 +125,7 @@ impl fmt::Debug for Rgba { #[derive(Debug, Clone, Copy)] pub enum Size { Original, - Thumbnail, + Thumbnail { width: u16 }, } #[derive(Debug, Clone)] @@ -117,6 +135,7 @@ pub enum Error { IOFailed(Arc), JoinFailed(Arc), ImageDecodingFailed(Arc), + BlurhashDecodingFailed(Arc), } impl From for Error { @@ -142,3 +161,9 @@ impl From for Error { Self::ImageDecodingFailed(Arc::new(error)) } } + +impl From for Error { + fn from(error: blurhash::Error) -> Self { + Self::BlurhashDecodingFailed(Arc::new(error)) + } +} -- cgit