Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171//! An image scaled down so neither edge passes a threshold. The aspect ratio is//! kept; provider fits keep JPEG as JPEG and turn anything else into PNG, while//! thumbnail fits encode lossy WebP.
use image::codecs::jpeg::JpegEncoder;use image::imageops::FilterType;use image::{DynamicImage, ImageFormat, ImageReader};use std::io::Cursor;use webp::{Encoder, WebPConfig};
const WEBP_QUALITY: f32 = 85.0;const WEBP_METHOD: i32 = 6;
pub struct Fitted { pub bytes: Vec<u8>, pub width: u32, pub height: u32, pub extension: &'static str,}
pub fn fit(bytes: &[u8], edge: u32) -> Result<Fitted, String> { let (format, resized) = decode_and_resize(bytes, edge)?; let width = resized.width(); let height = resized.height(); let mut out = Cursor::new(Vec::new()); let extension = match format { ImageFormat::Jpeg => { JpegEncoder::new_with_quality(&mut out, 90) .encode_image(&resized.to_rgb8()) .map_err(|e| e.to_string())?; "jpg" } _ => { resized .write_to(&mut out, ImageFormat::Png) .map_err(|e| e.to_string())?; "png" } }; Ok(Fitted { bytes: out.into_inner(), width, height, extension, })}
pub fn fit_webp(bytes: &[u8], edge: u32) -> Result<Fitted, String> { let (_, resized) = decode_and_resize(bytes, edge)?; let width = resized.width(); let height = resized.height(); let webp_bytes = encode_webp(&resized)?; Ok(Fitted { bytes: webp_bytes, width, height, extension: "webp", })}
fn decode_and_resize(bytes: &[u8], edge: u32) -> Result<(ImageFormat, DynamicImage), String> { let reader = ImageReader::new(Cursor::new(bytes)) .with_guessed_format() .map_err(|e| e.to_string())?; let format = reader.format().ok_or("not a PNG, JPEG, or WebP image")?; let image = reader .decode() .map_err(|e| format!("cannot decode the image: {e}"))?; let (width, height) = scaled(image.width(), image.height(), edge); let resized = if (width, height) == (image.width(), image.height()) { image } else { image.resize_exact(width, height, FilterType::Lanczos3) }; Ok((format, resized))}
fn encode_webp(image: &DynamicImage) -> Result<Vec<u8>, String> { let mut config = WebPConfig::new().map_err(|()| "cannot initialize WebP config")?; config.lossless = 0; config.quality = WEBP_QUALITY; config.method = WEBP_METHOD; config.use_sharp_yuv = 1; config.alpha_compression = 1;
let width = image.width(); let height = image.height(); let has_transparency = image.color().has_alpha() && match image.as_rgba8() { Some(rgba) => rgba.pixels().any(|p| p.0[3] < 255), None => image.to_rgba8().pixels().any(|p| p.0[3] < 255), };
let encoded = if has_transparency { let rgba = image.to_rgba8(); Encoder::from_rgba(rgba.as_raw(), width, height) .encode_advanced(&config) .map_err(|e| format!("cannot encode WebP: {e:?}"))? } else { let rgb = image.to_rgb8(); Encoder::from_rgb(rgb.as_raw(), width, height) .encode_advanced(&config) .map_err(|e| format!("cannot encode WebP: {e:?}"))? }; Ok(encoded.to_vec())}
/// The size `width` × `height` shrinks to so its longer edge is `edge`; an/// image already inside keeps its size.fn scaled(width: u32, height: u32, edge: u32) -> (u32, u32) { let longer = width.max(height); if longer <= edge { return (width, height); } let shrink = |side: u32| ((side as u64 * edge as u64 + longer as u64 / 2) / longer as u64).max(1) as u32; (shrink(width), shrink(height))}
#[cfg(test)]mod tests { use super::*; use image::{ImageBuffer, Rgba};
#[test] fn the_longer_edge_lands_on_the_limit() { assert_eq!(scaled(2304, 1212, 2000), (2000, 1052)); assert_eq!(scaled(1000, 8000, 2000), (250, 2000)); assert_eq!(scaled(1200, 800, 2000), (1200, 800)); assert_eq!(scaled(9000, 1, 2000), (2000, 1)); }
#[test] fn webp_fit_encodes_lossy_and_preserves_alpha() { let img = DynamicImage::ImageRgba8(ImageBuffer::from_fn(64, 32, |x, y| { let alpha = if x < 32 { 128 } else { 255 }; Rgba([(x * 4) as u8, (y * 8) as u8, 200, alpha]) })); let mut png = Cursor::new(Vec::new()); img.write_to(&mut png, ImageFormat::Png).unwrap(); let fitted = fit_webp(&png.into_inner(), 32).unwrap(); assert_eq!(fitted.extension, "webp"); assert_eq!((fitted.width, fitted.height), (32, 16)); assert_eq!(&fitted.bytes[..4], b"RIFF"); assert_eq!(&fitted.bytes[8..12], b"WEBP"); let decoded = image::load_from_memory(&fitted.bytes).unwrap(); assert_eq!((decoded.width(), decoded.height()), (32, 16)); assert!(decoded.color().has_alpha()); }
#[test] fn webp_fit_converts_jpeg_and_keeps_provider_fit_jpeg() { let img = DynamicImage::ImageRgb8(ImageBuffer::from_fn(64, 32, |x, y| { image::Rgb([(x * 4) as u8, (y * 8) as u8, 120]) })); let mut jpg = Cursor::new(Vec::new()); JpegEncoder::new_with_quality(&mut jpg, 90) .encode_image(&img.to_rgb8()) .unwrap(); let jpg_bytes = jpg.into_inner();
let provider = fit(&jpg_bytes, 32).unwrap(); assert_eq!(provider.extension, "jpg");
let thumb = fit_webp(&jpg_bytes, 32).unwrap(); assert_eq!(thumb.extension, "webp"); assert_eq!(&thumb.bytes[..4], b"RIFF"); assert_eq!(&thumb.bytes[8..12], b"WEBP"); }}