blurhash-rs icon indicating copy to clipboard operation
blurhash-rs copied to clipboard

How do convert the decoded result to a base64 encoded image?

Open dessalines opened this issue 2 months ago • 2 comments

I'd like to use this to serve base64 encoded image strings to a front end, but unfortunately its not clear how to do so.

This isn't working (maybe because the raw bytes don't produce an image?)

let decoded = blurhash::decode(blurhash, self.width.into(), self.height.into(), 1.0);
decoded.map(|data| general_purpose::STANDARD.encode(&data));

dessalines avatar Oct 19 '25 23:10 dessalines

Figured it out. This should probably be documented in the readme.

First you need to enable the image feature flag, and also add the image crate. Then:

/// Converts a blurhash string to a base64 png.
/// It's necessary to save it in the back-end, since this is too slow on the front end.
fn blurhash_to_base64_png(blurhash: &str, width: u32, height: u32) -> LemmyResult<String> {
  // Decode the blurhash into an image
  let decoded = blurhash::decode_image(blurhash, width, height, 1.0)?;

  // Create a base64 png string
  let base64 = image_to_base64_png(decoded)?;

  Ok(base64)
}

/// Converts an image to a base64 png
fn image_to_base64_png(image: ImageBuffer<Rgba<u8>, Vec<u8>>) -> LemmyResult<String> {
  use base64::{engine::general_purpose, Engine as _};
  use std::io::Cursor;

  let mut bytes: Vec<u8> = Vec::new();
  image.write_to(&mut Cursor::new(&mut bytes), image::ImageOutputFormat::Png)?;

  let b64_png = general_purpose::STANDARD.encode(bytes);
  Ok(b64_png)
}

dessalines avatar Oct 20 '25 00:10 dessalines

Documenting the image flag and crate in the README and main lib doc would be useful indeed! Patch is welcome.

rubdos avatar Oct 20 '25 11:10 rubdos