blurhash-rs
blurhash-rs copied to clipboard
How do convert the decoded result to a base64 encoded image?
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));
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)
}
Documenting the image flag and crate in the README and main lib doc would be useful indeed! Patch is welcome.