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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360//! 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::buffer::ConvertBuffer;use image::codecs::jpeg::JpegEncoder;use image::imageops::FilterType;use image::{ DynamicImage, GenericImageView, ImageBuffer, ImageDecoder, ImageFormat, ImageReader, Limits, Pixel, Primitive, Rgba, Rgba32FImage,};use std::io::Cursor;use webp::{Encoder, WebPConfig};
const WEBP_QUALITY: f32 = 85.0;const WEBP_METHOD: i32 = 6;const WEBP_MAX_EDGE: u32 = 16383;
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.min(WEBP_MAX_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 = decode_oriented(reader).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 { resize(&image, width, height) }; Ok((format, resized))}
fn decode_oriented(reader: ImageReader<Cursor<&[u8]>>) -> image::ImageResult<DynamicImage> { let mut decoder = reader.into_decoder()?; // Account for the decoded pixels against the same budget as ImageReader::decode. let mut limits = Limits::default(); limits.reserve(decoder.total_bytes())?; decoder.set_limits(limits)?; let orientation = decoder.orientation()?; let mut image = DynamicImage::from_decoder(decoder)?; image.apply_orientation(orientation); Ok(image)}
fn resize(image: &DynamicImage, width: u32, height: u32) -> DynamicImage { match image { DynamicImage::ImageLumaA8(pixels) => resize_with_alpha(pixels, width, height).into(), DynamicImage::ImageLumaA16(pixels) => resize_with_alpha(pixels, width, height).into(), DynamicImage::ImageRgba8(pixels) => resize_with_alpha(pixels, width, height).into(), DynamicImage::ImageRgba16(pixels) => resize_with_alpha(pixels, width, height).into(), DynamicImage::ImageRgba32F(pixels) => resize_with_alpha(pixels, width, height).into(), _ => image.resize_exact(width, height, FilterType::Lanczos3), }}
fn resize_with_alpha<P>( pixels: &ImageBuffer<P, Vec<P::Subpixel>>, width: u32, height: u32,) -> ImageBuffer<P, Vec<P::Subpixel>>where P: Pixel, P::Subpixel: Into<f32>, Rgba32FImage: ConvertBuffer<ImageBuffer<P, Vec<P::Subpixel>>>,{ // Lanczos samples channels independently. Associate color with alpha // during sampling so invisible source colors cannot tint visible edges. let mut resized = image::imageops::resize(&Premultiplied(pixels), width, height, FilterType::Lanczos3); for pixel in resized.pixels_mut() { let [red, green, blue, alpha] = pixel.0; *pixel = if alpha > 0.0 { Rgba([red / alpha, green / alpha, blue / alpha, alpha]) } else { Rgba([0.0; 4]) }; } resized.convert()}
// Present premultiplied samples without allocating another full-size input.struct Premultiplied<'a, P: Pixel>(&'a ImageBuffer<P, Vec<P::Subpixel>>);
impl<P: Pixel> GenericImageView for Premultiplied<'_, P>where P::Subpixel: Into<f32>,{ type Pixel = Rgba<f32>;
fn dimensions(&self) -> (u32, u32) { self.0.dimensions() }
fn get_pixel(&self, x: u32, y: u32) -> Self::Pixel { let scale = P::Subpixel::DEFAULT_MAX_VALUE.into(); let [red, green, blue, alpha] = self .0 .get_pixel(x, y) .to_rgba() .0 .map(|sample| sample.into() / scale); Rgba([red * alpha, green * alpha, blue * alpha, alpha]) }
fn buffer_with_dimensions(&self, width: u32, height: u32) -> Rgba32FImage { let mut buffer = Rgba32FImage::new(width, height); buffer .set_color_space(self.0.color_space()) .expect("color space from an image buffer is RGB"); buffer }}
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 proptest::prelude::*;
proptest! { #![proptest_config(crate::property::config(256))]
// An image larger than the edge shrinks so its longer side lands on // the edge, keeps its aspect within rounding, and never loses a side. #[test] fn scaled_fits_the_longer_side_to_the_edge( width in 1u32..20_000, height in 1u32..20_000, edge in 1u32..20_000, ) { let (w, h) = scaled(width, height, edge); let longer = width.max(height); prop_assert_eq!(w.max(h), longer.min(edge)); prop_assert!(w >= 1 && h >= 1); if longer <= edge { prop_assert_eq!((w, h), (width, height)); } else { // w / edge differs from width / longer by at most half a pixel. let exact = |side: u32, got: u32| { (got as i64 * longer as i64 - side as i64 * edge as i64).abs() * 2 <= longer as i64 || got == 1 }; prop_assert!(exact(width, w) && exact(height, h)); } } }
#[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_respects_the_codec_limit() { let mut png = Cursor::new(Vec::new()); DynamicImage::new_rgb8(16384, 1) .write_to(&mut png, ImageFormat::Png) .unwrap(); let input = png.into_inner();
let fitted = fit_webp(&input, 16384).unwrap(); let decoded = image::load_from_memory_with_format(&fitted.bytes, ImageFormat::WebP).unwrap(); assert_eq!((fitted.width, fitted.height), (16383, 1)); assert_eq!((decoded.width(), decoded.height()), (16383, 1)); assert_eq!(fit(&input, 16384).unwrap().width, 16384); }
#[test] fn fitting_a_camera_jpeg_keeps_its_display_orientation() { use image::ImageEncoder;
let source = ImageBuffer::from_fn(40, 20, |x, _| { let shade: u8 = if x < 20 { 32 } else { 224 }; image::Rgb([shade; 3]) }); let mut jpeg = Vec::new(); let mut encoder = JpegEncoder::new_with_quality(&mut jpeg, 90); // A little-endian TIFF IFD containing only EXIF orientation 6 (90° clockwise). encoder .set_exif_metadata( b"II\x2a\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0\x06\0\0\0\0\0\0\0".to_vec(), ) .unwrap(); encoder.encode_image(&source).unwrap();
for fitted in [fit(&jpeg, 20).unwrap(), fit_webp(&jpeg, 20).unwrap()] { let decoded = image::load_from_memory(&fitted.bytes).unwrap().to_rgb8(); assert_eq!((fitted.width, fitted.height), (10, 20)); assert_eq!(decoded.dimensions(), (10, 20)); assert!(decoded.get_pixel(5, 2)[0] < 128); assert!(decoded.get_pixel(5, 17)[0] > 128); } }
#[test] fn transparent_source_colors_do_not_bleed_into_visible_pixels() { let png = |hidden_red| { let image = DynamicImage::ImageRgba8(ImageBuffer::from_fn(32, 8, |x, _| { if x < 16 { Rgba([0, 0, 0, 255]) } else { Rgba([hidden_red, 0, 0, 0]) } })); let mut bytes = Cursor::new(Vec::new()); image.write_to(&mut bytes, ImageFormat::Png).unwrap(); bytes.into_inner() };
for fit in [fit, fit_webp] { let decode = |hidden_red| { let output = fit(&png(hidden_red), 16).unwrap(); image::load_from_memory(&output.bytes).unwrap().to_rgba8() }; let clean = decode(0); let tinted = decode(255); assert!(clean.pixels().any(|pixel| (1..255).contains(&pixel[3]))); assert!( clean .pixels() .zip(tinted.pixels()) .all(|(a, b)| { a[3] == b[3] && (a[3] == 0 || a == b) }), "hidden RGB affected the fitted pixels" ); } }
#[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"); }}