use image::{DynamicImage, GenericImageView}; use serde::{Deserialize, Serialize}; use crate::encode::{EncodeOptions, encode, fit_within}; use crate::error::{RasterError, Result}; use crate::ops::resize_exact; use crate::{Format, Limits}; /// Batch-resize presets of the Toolbox. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum Preset { /// Long edge 1600 px, JPEG quality 80. Email, /// Long edge 2048 px, JPEG quality 85; an image with real transparency is written as PNG instead. Web, /// No resize, the source format (HEIC/AVIF, which cannot be written, become JPEG at the default quality). Original, } /// Apply a preset; returns the encoded bytes and the format they are in. Never enlarges. pub fn apply_preset(img: &DynamicImage, src_format: Format, preset: Preset) -> Result<(Vec, Format)> { let shrink = |long: u32| { let (w, h) = img.dimensions(); let (nw, nh) = fit_within(w, h, long); if (nw, nh) == (w, h) { std::borrow::Cow::Borrowed(img) } else { std::borrow::Cow::Owned(resize_exact(img, nw, nh)) } }; let jpeg = |q: u8| EncodeOptions { jpeg_quality: q, ..EncodeOptions::default() }; match preset { Preset::Email => Ok((encode(&shrink(1600), Format::Jpeg, &jpeg(80))?, Format::Jpeg)), Preset::Web => { let small = shrink(2048); if has_transparency(&small) { Ok((encode(&small, Format::Png, &EncodeOptions::default())?, Format::Png)) } else { Ok((encode(&small, Format::Jpeg, &jpeg(85))?, Format::Jpeg)) } } Preset::Original => { let format = if src_format.can_encode() { src_format } else { Format::Jpeg }; Ok((encode(img, format, &EncodeOptions::default())?, format)) } } } /// An alpha channel with at least one pixel that is not fully opaque. pub fn has_transparency(img: &DynamicImage) -> bool { match img { DynamicImage::ImageRgba8(b) => b.pixels().any(|p| p.0[3] < 255), DynamicImage::ImageLumaA8(b) => b.pixels().any(|p| p.0[1] < 255), DynamicImage::ImageRgba16(b) => b.pixels().any(|p| p.0[3] < u16::MAX), DynamicImage::ImageLumaA16(b) => b.pixels().any(|p| p.0[1] < u16::MAX), other if other.color().has_alpha() => other.to_rgba8().pixels().any(|p| p.0[3] < 255), _ => false, } } /// Result of [`compress_to`]. #[derive(Debug, Clone, PartialEq)] pub struct Compressed { pub bytes: Vec, pub format: Format, /// JPEG quality used; `None` for lossless formats. pub quality: Option, /// Output long edge divided by the input long edge (1.0 = full size). pub scale: f32, pub width: u32, pub height: u32, } const JPEG_MIN_Q: u8 = 40; const JPEG_MAX_Q: u8 = 92; const JPEG_SCALED_Q: u8 = 75; const SCALE_STEP: f64 = 0.85; const MIN_LONG_EDGE: u32 = 320; /// Make the encoded image fit in `target_bytes`. /// /// JPEG: the highest quality in 40..=92 that fits at full size (binary search). If even quality 40 is too /// large, the image is shrunk in 0.85 steps at quality 75 until it fits; the last step that keeps the long edge /// at 320 px or more is also tried at quality 40. PNG, WebP (lossless) and the other lossless formats: the /// 0.85 shrink steps only. Below 320 px: [`RasterError::CannotReachTarget`] with the smallest size seen. pub fn compress_to(img: &DynamicImage, format: Format, target_bytes: u64, limits: &Limits) -> Result { if !format.can_encode() { return Err(RasterError::CannotWrite { format }); } if target_bytes == 0 { return Err(RasterError::InvalidTarget); } let (w, h) = img.dimensions(); crate::decode::check_pixels(w, h, limits)?; let jpeg = format == Format::Jpeg; let run = |im: &DynamicImage, q: Option| -> Result> { let options = EncodeOptions { jpeg_quality: q.unwrap_or(88), ..EncodeOptions::default() }; encode(im, format, &options) }; let fits = |b: &[u8]| b.len() as u64 <= target_bytes; let done = |bytes: Vec, quality: Option, nw: u32, nh: u32| Compressed { bytes, format, quality, scale: nw.max(nh) as f32 / w.max(h) as f32, width: nw, height: nh, }; let mut smallest = u64::MAX; if jpeg { let at_max = run(img, Some(JPEG_MAX_Q))?; if fits(&at_max) { return Ok(done(at_max, Some(JPEG_MAX_Q), w, h)); } let at_min = run(img, Some(JPEG_MIN_Q))?; smallest = smallest.min(at_min.len() as u64); if fits(&at_min) { // Invariant: `lo` fits, `hi` does not. let (mut lo, mut hi, mut best) = (JPEG_MIN_Q, JPEG_MAX_Q, at_min); while hi - lo > 1 { let mid = lo + (hi - lo) / 2; let b = run(img, Some(mid))?; if fits(&b) { lo = mid; best = b; } else { hi = mid; } } return Ok(done(best, Some(lo), w, h)); } } else { let full = run(img, None)?; smallest = smallest.min(full.len() as u64); if fits(&full) { return Ok(done(full, None, w, h)); } } let quality = jpeg.then_some(JPEG_SCALED_Q); let long = w.max(h); let mut scale = 1.0f64; let mut last: Option = None; loop { scale *= SCALE_STEP; let new_long = (f64::from(long) * scale).round() as u32; if new_long < MIN_LONG_EDGE { break; } let (nw, nh) = fit_within(w, h, new_long); let small = resize_exact(img, nw, nh); let b = run(&small, quality)?; smallest = smallest.min(b.len() as u64); if fits(&b) { return Ok(done(b, quality, nw, nh)); } last = Some(small); } if jpeg && let Some(small) = last { let b = run(&small, Some(JPEG_MIN_Q))?; smallest = smallest.min(b.len() as u64); if fits(&b) { return Ok(done(b, Some(JPEG_MIN_Q), small.width(), small.height())); } } Err(RasterError::CannotReachTarget { smallest_bytes: smallest }) }