Skip to content

Commit

Permalink
Add blurhash to gallery
Browse files Browse the repository at this point in the history
  • Loading branch information
tarkah committed Feb 6, 2025
1 parent 4bbb5cb commit ab23637
Show file tree
Hide file tree
Showing 4 changed files with 191 additions and 38 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions examples/gallery/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,7 @@ bytes.workspace = true
image.workspace = true
tokio.workspace = true

blurhash = "0.2.3"

[lints]
workspace = true
33 changes: 29 additions & 4 deletions examples/gallery/src/civitai.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::sync::Arc;
pub struct Image {
pub id: Id,
url: String,
hash: String,
}

impl Image {
Expand Down Expand Up @@ -40,20 +41,37 @@ impl Image {
Ok(response.items)
}

pub async fn blurhash(
self,
width: u32,
height: u32,
) -> Result<Rgba, Error> {
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<Rgba, Error> {
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::<Vec<_>>()
Expand Down Expand Up @@ -107,7 +125,7 @@ impl fmt::Debug for Rgba {
#[derive(Debug, Clone, Copy)]
pub enum Size {
Original,
Thumbnail,
Thumbnail { width: u16 },
}

#[derive(Debug, Clone)]
Expand All @@ -117,6 +135,7 @@ pub enum Error {
IOFailed(Arc<io::Error>),
JoinFailed(Arc<task::JoinError>),
ImageDecodingFailed(Arc<image::ImageError>),
BlurhashDecodingFailed(Arc<blurhash::Error>),
}

impl From<reqwest::Error> for Error {
Expand All @@ -142,3 +161,9 @@ impl From<image::ImageError> for Error {
Self::ImageDecodingFailed(Arc::new(error))
}
}

impl From<blurhash::Error> for Error {
fn from(error: blurhash::Error) -> Self {
Self::BlurhashDecodingFailed(Arc::new(error))
}
}
Loading

0 comments on commit ab23637

Please sign in to comment.