Files
Pictor-public/crates/raster/src/ops.rs
T

107 lines
3.8 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use image::imageops::FilterType;
use image::{DynamicImage, GenericImageView};
use serde::{Deserialize, Serialize};
use crate::Limits;
use crate::encode::fit_within;
use crate::error::{RasterError, Result};
/// A crop rectangle in pixels, origin at the top left.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rect {
pub x: u32,
pub y: u32,
pub width: u32,
pub height: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Rotation {
/// 90° clockwise.
Cw90,
/// 90° counter-clockwise.
Ccw90,
R180,
/// Mirror left-right.
FlipH,
/// Mirror top-bottom.
FlipV,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum Fit {
/// Shrink so the longer side is at most this many pixels; never enlarges.
LongEdge(u32),
/// Exactly this size (aspect ratio not kept; may enlarge, within `Limits`).
Exact(u32, u32),
/// Scale both sides by this percentage (100 = unchanged); each side is at least 1 pixel.
Percent(f32),
}
/// Cut out `rect`; it must lie fully inside the image and be at least 1 × 1.
pub fn crop(img: &DynamicImage, rect: Rect) -> Result<DynamicImage> {
let (w, h) = img.dimensions();
let right = rect.x.checked_add(rect.width).ok_or(RasterError::InvalidCrop)?;
let bottom = rect.y.checked_add(rect.height).ok_or(RasterError::InvalidCrop)?;
if rect.width == 0 || rect.height == 0 || right > w || bottom > h {
return Err(RasterError::InvalidCrop);
}
Ok(img.crop_imm(rect.x, rect.y, rect.width, rect.height))
}
pub fn rotate(img: &DynamicImage, rotation: Rotation) -> DynamicImage {
match rotation {
Rotation::Cw90 => img.rotate90(),
Rotation::Ccw90 => img.rotate270(),
Rotation::R180 => img.rotate180(),
Rotation::FlipH => img.fliph(),
Rotation::FlipV => img.flipv(),
}
}
/// Resize with Lanczos3 when shrinking and Catmull-Rom when enlarging. The result is checked against
/// `limits.max_pixels` and `limits.max_alloc` before any buffer is made.
pub fn resize(img: &DynamicImage, fit: Fit, limits: &Limits) -> Result<DynamicImage> {
let (w, h) = img.dimensions();
let (nw, nh) = target_size(w, h, fit)?;
if (nw, nh) == (w, h) {
return Ok(img.clone());
}
let pixels = u64::from(nw) * u64::from(nh);
if pixels > limits.max_pixels {
return Err(RasterError::TooManyPixels { width: nw.into(), height: nh.into() });
}
// Output buffer plus `image`'s f32 intermediate (one pass, 4 channels).
let bpp = u64::from(img.color().bytes_per_pixel());
let needed =
pixels.saturating_mul(bpp).saturating_add(u64::from(nw).saturating_mul(u64::from(h)).saturating_mul(16));
if needed > limits.max_alloc {
return Err(RasterError::TooMuchMemory { limit: limits.max_alloc });
}
Ok(resize_exact(img, nw, nh))
}
pub(crate) fn resize_exact(img: &DynamicImage, nw: u32, nh: u32) -> DynamicImage {
let (w, h) = img.dimensions();
let filter = if nw <= w && nh <= h { FilterType::Lanczos3 } else { FilterType::CatmullRom };
img.resize_exact(nw, nh, filter)
}
fn target_size(w: u32, h: u32, fit: Fit) -> Result<(u32, u32)> {
match fit {
Fit::LongEdge(0) | Fit::Exact(0, _) | Fit::Exact(_, 0) => Err(RasterError::InvalidSize),
Fit::LongEdge(n) => Ok(fit_within(w, h, n)),
Fit::Exact(nw, nh) => Ok((nw, nh)),
Fit::Percent(p) => {
if !p.is_finite() || p <= 0.0 {
return Err(RasterError::InvalidSize);
}
let side = |v: u32| -> Result<u32> {
let s = (f64::from(v) * f64::from(p) / 100.0).round().max(1.0);
if s > f64::from(u32::MAX) { Err(RasterError::InvalidSize) } else { Ok(s as u32) }
};
Ok((side(w)?, side(h)?))
}
}
}