Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add blurhash to gallery #2796

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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