2022-02-15 20:18:17 +00:00
|
|
|
use blurhash::{decode, encode};
|
2022-02-24 01:11:14 +00:00
|
|
|
use image::GenericImageView;
|
2022-02-15 20:18:17 +00:00
|
|
|
use std::env;
|
|
|
|
use std::fs;
|
|
|
|
use std::path::Path;
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
enum ImageDataErrors {
|
2022-02-24 01:11:14 +00:00
|
|
|
// ...
|
|
|
|
BufferTooSmall,
|
2022-02-15 20:18:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
struct FloatingImage {
|
2022-02-24 01:11:14 +00:00
|
|
|
width: u32,
|
|
|
|
height: u32,
|
|
|
|
data: Vec<u8>,
|
|
|
|
name: String,
|
2022-02-15 20:18:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl FloatingImage {
|
2022-02-24 01:11:14 +00:00
|
|
|
fn new(width: u32, height: u32, name: &String) -> Self {
|
|
|
|
let buffer_capacity = 3_655_744;
|
|
|
|
let buffer: Vec<u8> = Vec::with_capacity(buffer_capacity);
|
|
|
|
FloatingImage {
|
|
|
|
width,
|
|
|
|
height,
|
|
|
|
data: buffer,
|
|
|
|
name: name.to_string(),
|
|
|
|
}
|
2022-02-15 20:18:17 +00:00
|
|
|
}
|
|
|
|
|
2022-02-24 01:11:14 +00:00
|
|
|
fn set_data(&mut self, data: Vec<u8>) -> Result<(), ImageDataErrors> {
|
|
|
|
// If the previously assigned buffer is too small to hold the new data
|
|
|
|
if data.len() > self.data.capacity() {
|
|
|
|
return Err(ImageDataErrors::BufferTooSmall);
|
|
|
|
}
|
|
|
|
self.data = data;
|
|
|
|
Ok(())
|
2022-02-15 20:18:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() -> Result<(), ImageDataErrors> {
|
|
|
|
let args: Vec<String> = env::args().collect();
|
|
|
|
// Add image to your Cargo.toml
|
|
|
|
let img = image::open(&args[1]).unwrap();
|
|
|
|
let (width, height) = img.dimensions();
|
|
|
|
let blurhash = encode(4, 3, width, height, &img.to_rgba8().into_vec()).unwrap();
|
|
|
|
|
|
|
|
println!("{}", &blurhash);
|
|
|
|
let pixels = decode(&blurhash, 50, 50, 1.0).unwrap();
|
|
|
|
|
2022-02-15 20:56:37 +00:00
|
|
|
let mut output = FloatingImage::new(50, 50, &args[2]);
|
2022-02-15 20:18:17 +00:00
|
|
|
output.set_data(pixels)?;
|
|
|
|
image::save_buffer_with_format(
|
2022-02-24 01:11:14 +00:00
|
|
|
output.name,
|
|
|
|
&output.data,
|
|
|
|
output.width,
|
|
|
|
output.height,
|
|
|
|
image::ColorType::Rgba8,
|
|
|
|
image::ImageFormat::Png,
|
|
|
|
)
|
|
|
|
.unwrap();
|
2022-02-15 20:18:17 +00:00
|
|
|
Ok(())
|
|
|
|
}
|