aviary-cli/src/thumbnailing.rs

26 lines
914 B
Rust
Raw Normal View History

use std::io::Cursor;
use image::{io::Reader, DynamicImage, ImageResult};
use webp::{Encoder, WebPMemory};
pub fn thumbnail(bytes: &[u8]) -> ImageResult<(WebPMemory, String)> {
let original_image = Reader::new(Cursor::new(bytes))
.with_guessed_format().expect("IO errors impossible with Cursor")
.decode()?;
let new_dimm = u32::min(original_image.height(), original_image.width());
let crop_x = (original_image.width() - new_dimm) / 2;
let crop_y = (original_image.height() - new_dimm) / 2;
let cropped = original_image.crop_imm(crop_x, crop_y, new_dimm, new_dimm);
let scaled = if new_dimm < 400 {
cropped
} else {
original_image.thumbnail_exact(400, 400)
}.into_rgba8();
let blurhash = blurhash::encode(4, 4, 400, 400, scaled.as_raw());
Ok((
Encoder::from_image(&DynamicImage::ImageRgba8(scaled))
.expect("Unexpected difficulty interpretting thumbnail")
.encode(50.0),
blurhash
))
}