Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Image Size: Photoshop's resampling, measured (#2451)

Unemars0b4b1e428643
diff --git a/crates/algo/src/resample.rs b/crates/algo/src/resample.rs
index 918eb899a..bd728e379 100644
--- a/crates/algo/src/resample.rs
+++ b/crates/algo/src/resample.rs
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use crate::image::{premultiply, unpremultiply};
-/// Resampling method (Photoshop's Image Size options).
+/// Resampling method (Photoshop's Image Size options, and Lanczos).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub enum Resample {
@@ -14,51 +14,121 @@ pub enum Resample {
Bilinear,
#[default]
Bicubic,
+ /// Photoshop's Bicubic Smoother, for enlargement.
+ BicubicSmoother,
+ /// Photoshop's Bicubic Sharper, for reduction.
+ BicubicSharper,
+ /// Photoshop's Bicubic Automatic: Smoother where the image grows, Sharper where it shrinks.
+ BicubicAutomatic,
Lanczos,
- /// Lanczos followed by a light sharpening when enlarging.
+ /// Lanczos followed by a light sharpening when enlarging; Bicubic Sharper when reducing, as
+ /// Photoshop's Preserve Details reduces.
PreserveDetails,
}
-impl Resample {
- fn support(self) -> f64 {
- match self {
- Resample::Nearest => 0.5,
- Resample::Bilinear => 1.0,
- Resample::Bicubic => 2.0,
- Resample::Lanczos | Resample::PreserveDetails => 3.0,
- }
+/// Sub-pixel positions Photoshop's filters resolve: a sample's offset is rounded to 1/128 pixel.
+const PHASES: f64 = 128.0;
+
+/// The filter of one axis.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Kernel {
+ Nearest,
+ /// Linear interpolation, never widened. Below half size, each output pixel is the plain
+ /// average of the source pixels it covers.
+ Bilinear,
+ /// The Keys cubic with parameter `a`, stretched over `stretch` source pixels.
+ Keys {
+ a: f64,
+ stretch: f64,
+ },
+ /// Lanczos-3, widened by 1/scale when reducing.
+ Lanczos,
+}
+
+/// Photoshop's bicubic filters, measured on Photoshop 25.4 (the Keys cubic, phase table and
+/// stretch fitted to within 1/4000 of every weight). `s` is the scale the filter is designed for.
+///
+/// - Bicubic: a = −0.75.
+/// - Bicubic Smoother: stretched by 1.15; a = −0.625, and −0.625 − 0.5·(1 − s) when reducing.
+/// - Bicubic Sharper: stretched by 1.05; a = −1, and −1 − 1.6·(1 − s) when reducing.
+///
+/// Reducing widens the filter by 1/s, down to ¼; below that [`taps`] first averages the image
+/// down to four times the target.
+fn keys(method: Resample, s: f64) -> Kernel {
+ let s = s.clamp(0.25, 1.0);
+ let (a, stretch) = match method {
+ Resample::BicubicSmoother => (-0.625 - 0.5 * (1.0 - s), 1.15),
+ Resample::BicubicSharper => (-1.0 - 1.6 * (1.0 - s), 1.05),
+ _ => (-0.75, 1.0),
+ };
+ Kernel::Keys { a, stretch: stretch / s }
+}
+
+fn keys_weight(x: f64, a: f64) -> f64 {
+ let x = x.abs();
+ if x < 1.0 {
+ (a + 2.0) * x * x * x - (a + 3.0) * x * x + 1.0
+ } else if x < 2.0 {
+ a * (x * x * x - 5.0 * x * x + 8.0 * x - 4.0)
+ } else {
+ 0.0
}
- fn weight(self, x: f64) -> f64 {
- let x = x.abs();
- match self {
- Resample::Nearest => {
- if x <= 0.5 {
- 1.0
- } else {
- 0.0
- }
- }
- Resample::Bilinear => (1.0 - x).max(0.0),
- Resample::Bicubic => {
- // Keys cubic, a = -0.5 (Catmull-Rom).
- let a = -0.5;
- if x < 1.0 {
- (a + 2.0) * x * x * x - (a + 3.0) * x * x + 1.0
- } else if x < 2.0 {
- a * x * x * x - 5.0 * a * x * x + 8.0 * a * x - 4.0 * a
- } else {
- 0.0
- }
+}
+
+fn lanczos_weight(x: f64) -> f64 {
+ let x = x.abs();
+ if x < 1e-9 {
+ 1.0
+ } else if x < 3.0 {
+ let px = std::f64::consts::PI * x;
+ 3.0 * px.sin() * (px / 3.0).sin() / (px * px)
+ } else {
+ 0.0
+ }
+}
+
+/// One resampling pass: scale factors and the filter of each axis.
+#[derive(Clone, Copy, Debug)]
+struct Pass {
+ sx: f64,
+ sy: f64,
+ kx: Kernel,
+ ky: Kernel,
+}
+
+/// Photoshop's passes for `filter` at `(sx, sy)`.
+///
+/// A bicubic filter is designed for the height's scale, or the width's when the height stays,
+/// and serves both axes; the axis with the smaller scale goes first, and the image is clipped and
+/// stored between the passes. Bicubic Automatic with one axis growing and the other shrinking is
+/// two Image Sizes: the shrinking axis with Sharper, then the growing one with Smoother, each
+/// designed for its own scale. Nearest, Bilinear and Lanczos run both axes in one pass.
+fn plan(filter: Resample, sx: f64, sy: f64) -> Vec<Pass> {
+ let both = |k: Kernel| vec![Pass { sx, sy, kx: k, ky: k }];
+ match filter {
+ Resample::Nearest => both(Kernel::Nearest),
+ Resample::Bilinear => both(Kernel::Bilinear),
+ Resample::Lanczos => both(Kernel::Lanczos),
+ Resample::PreserveDetails if sx > 1.0 || sy > 1.0 => both(Kernel::Lanczos),
+ Resample::PreserveDetails => plan(Resample::BicubicSharper, sx, sy),
+ Resample::BicubicAutomatic if sx <= 1.0 && sy <= 1.0 => plan(Resample::BicubicSharper, sx, sy),
+ Resample::BicubicAutomatic if sx >= 1.0 && sy >= 1.0 => plan(Resample::BicubicSmoother, sx, sy),
+ Resample::BicubicAutomatic => {
+ let (sharper, smoother) = (Resample::BicubicSharper, Resample::BicubicSmoother);
+ if sx < 1.0 {
+ vec![Pass { sx, sy: 1.0, kx: keys(sharper, sx), ky: Kernel::Nearest }, Pass { sx: 1.0, sy, kx: Kernel::Nearest, ky: keys(smoother, sy) }]
+ } else {
+ vec![Pass { sx: 1.0, sy, kx: Kernel::Nearest, ky: keys(sharper, sy) }, Pass { sx, sy: 1.0, kx: keys(smoother, sx), ky: Kernel::Nearest }]
}
- Resample::Lanczos | Resample::PreserveDetails => {
- if x < 1e-9 {
- 1.0
- } else if x < 3.0 {
- let px = std::f64::consts::PI * x;
- 3.0 * px.sin() * (px / 3.0).sin() / (px * px)
- } else {
- 0.0
- }
+ }
+ Resample::Bicubic | Resample::BicubicSmoother | Resample::BicubicSharper => {
+ let k = keys(filter, if sy != 1.0 { sy } else { sx });
+ if sx == 1.0 || sy == 1.0 {
+ both(k)
+ } else if sy < sx {
+ vec![Pass { sx: 1.0, sy, kx: k, ky: k }, Pass { sx, sy: 1.0, kx: k, ky: k }]
+ } else {
+ vec![Pass { sx, sy: 1.0, kx: k, ky: k }, Pass { sx: 1.0, sy, kx: k, ky: k }]
}
}
}
@@ -72,36 +142,91 @@ struct Taps {
outside: f32,
}
-/// Taps for mapping output coordinate `o` (in `[dst0, dst1)`) to the source
-/// via `u = (o + 0.5) / scale - 0.5`. With `edge` (`[first, last]` source index), taps outside it
-/// read the nearest sample inside it: the image repeats its edge instead of fading out.
+/// The source position of output sample `o`, `(o + 0.5) / scale − 0.5`, kept on the edge
+/// samples (`[first, last]`) when there is an edge, and rounded to Photoshop's 1/128 pixel.
+fn position(o: i32, scale: f64, edge: Option<(i32, i32)>) -> f64 {
+ let mut u = (o as f64 + 0.5) / scale - 0.5;
+ if let Some((a, b)) = edge {
+ u = u.clamp(a as f64, b.max(a) as f64);
+ }
+ let j = u.floor();
+ j + ((u - j) * PHASES).round() / PHASES
+}
+
+/// The source pixels `[floor(o / scale), floor((o + 1) / scale))` output pixel `o` covers.
+fn cover(o: i32, scale: f64) -> (i32, i32) {
+ let a = (o as f64 / scale + 1e-9).floor() as i32;
+ (a, ((o + 1) as f64 / scale + 1e-9).floor().max(a as f64 + 1.0) as i32)
+}
+
+/// Unclamped weights of output sample `o` over source samples `lo..lo + len`.
+fn weights(o: i32, scale: f64, kernel: Kernel, edge: Option<(i32, i32)>) -> (i32, Vec<f64>) {
+ match kernel {
+ Kernel::Nearest => {
+ let u = (o as f64 + 0.5) / scale - 0.5;
+ ((u + 0.5).floor() as i32, vec![1.0])
+ }
+ Kernel::Bilinear if scale < 0.5 => {
+ let (a, b) = cover(o, scale);
+ (a, vec![1.0 / (b - a) as f64; (b - a) as usize])
+ }
+ Kernel::Bilinear => {
+ let u = position(o, scale, edge);
+ let j = u.floor();
+ (j as i32, vec![1.0 - (u - j), u - j])
+ }
+ Kernel::Keys { a, stretch } if scale < 0.25 => {
+ // Averaged down to four times the target first (pixels of `inner`), then filtered.
+ let inner = 4.0 * scale;
+ let inner_edge = edge.map(|(a, b)| ((a as f64 * inner - 1e-9).ceil() as i32, ((b + 1) as f64 * inner - 1e-9).ceil() as i32 - 1));
+ let (k0, kw) = weights(o, 0.25, Kernel::Keys { a, stretch }, inner_edge);
+ let clamp = |k: i32| inner_edge.map_or(k, |(a, b)| k.clamp(a, b.max(a)));
+ let boxes: Vec<(i32, i32)> = (k0..).zip(&kw).map(|(k, _)| cover(clamp(k), inner)).collect();
+ let lo = boxes.iter().map(|b| b.0).min().unwrap_or(0);
+ let hi = boxes.iter().map(|b| b.1).max().unwrap_or(lo);
+ let mut w = vec![0.0; (hi - lo).max(0) as usize];
+ for ((a, b), v) in boxes.into_iter().zip(kw) {
+ for slot in w.get_mut((a - lo) as usize..(b - lo) as usize).into_iter().flatten() {
+ *slot += v / (b - a) as f64;
+ }
+ }
+ (lo, w)
+ }
+ Kernel::Keys { a, stretch } => {
+ let u = position(o, scale, edge);
+ let lo = (u - 2.0 * stretch).floor() as i32;
+ let hi = (u + 2.0 * stretch).ceil() as i32;
+ let w: Vec<f64> = (lo..=hi).map(|i| keys_weight((u - i as f64) / stretch, a)).collect();
+ let sum: f64 = w.iter().sum();
+ (lo, w.into_iter().map(|v| v / sum).collect())
+ }
+ Kernel::Lanczos => {
+ let stretch = if scale < 1.0 { 1.0 / scale } else { 1.0 };
+ let u = (o as f64 + 0.5) / scale - 0.5;
+ let u = edge.map_or(u, |(a, b)| u.clamp(a as f64, b.max(a) as f64));
+ let lo = (u - 3.0 * stretch).ceil() as i32;
+ let hi = (u + 3.0 * stretch).floor() as i32;
+ let w: Vec<f64> = (lo..=hi).map(|i| lanczos_weight((i as f64 - u) / stretch)).collect();
+ let sum: f64 = w.iter().sum();
+ let k = if sum.abs() > 1e-12 { 1.0 / sum } else { 1.0 };
+ (lo, w.into_iter().map(|v| v * k).collect())
+ }
+ }
+}
+
+/// Taps for mapping output coordinate `o` (in `[dst0, dst1)`) to the source at `scale`
+/// (a scale of 1 copies). With `edge` (`[first, last]` source index), taps outside it read the
+/// nearest sample inside it: the image repeats its edge instead of fading out.
/// Taps outside `content` (`[first, last]`) all read the default pixel, so they are folded into
/// `outside` instead of being read: the read window never grows past the content, however small
/// the scale (#713).
-fn taps(dst0: i32, dst1: i32, scale: f64, filter: Resample, edge: Option<(i32, i32)>, content: (i32, i32)) -> Vec<Taps> {
- let stretch = if scale < 1.0 { 1.0 / scale } else { 1.0 };
- let support = filter.support() * stretch;
+fn taps(dst0: i32, dst1: i32, scale: f64, kernel: Kernel, edge: Option<(i32, i32)>, content: (i32, i32)) -> Vec<Taps> {
let clamp = |i: i32| edge.map_or(i, |(a, b)| i.clamp(a, b));
+ let kernel = if scale == 1.0 { Kernel::Nearest } else { kernel };
(dst0..dst1)
.map(|o| {
- let u = (o as f64 + 0.5) / scale - 0.5;
- if filter == Resample::Nearest {
- let i = clamp((u + 0.5).floor() as i32);
- return if (content.0..=content.1).contains(&i) {
- Taps { start: i, weights: vec![1.0], outside: 0.0 }
- } else {
- Taps { start: content.0, weights: Vec::new(), outside: 1.0 }
- };
- }
- let lo = (u - support).ceil() as i32;
- let hi = (u + support).floor() as i32;
- let mut w: Vec<f64> = (lo..=hi).map(|i| filter.weight((i as f64 - u) / stretch)).collect();
- let s: f64 = w.iter().sum();
- if s.abs() > 1e-12 {
- for v in &mut w {
- *v /= s;
- }
- }
+ let (lo, w) = weights(o, scale, kernel, edge);
+ let hi = lo + w.len() as i32 - 1;
// Fold the weights of taps beyond the edge onto the edge sample.
let start = clamp(lo);
let mut folded = vec![0.0f32; (clamp(hi) - start + 1).max(1) as usize];
@@ -141,8 +266,7 @@ pub fn resize_surface(s: &Surface, sx: f64, sy: f64, filter: Resample) -> Surfac
/// keeps it (an opaque layer stays opaque to the border) instead of fading into the default pixel.
/// Pixels beyond the canvas count as the surface's own, and inside the canvas nothing changes.
pub fn resize_surface_in_canvas(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Rect) -> Surface {
- let area = s.content_bounds().union(&canvas);
- resize(s, sx, sy, filter, (!area.is_empty()).then_some(area))
+ resize(s, sx, sy, filter, Some(canvas))
}
/// Samples one source read may hold (64 MB of `f32`); larger windows are read in row chunks.
@@ -183,11 +307,37 @@ fn horizontal_dynamic(row: &[f32], out: &mut [f32], taps: &[Taps], x_lo: i32, de
}
}
-fn resize(s: &Surface, sx: f64, sy: f64, filter: Resample, edge: Option<Rect>) -> Surface {
- resize_with_budget(s, sx, sy, filter, edge, READ_BUDGET)
+fn resize(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Option<Rect>) -> Surface {
+ resize_with_budget(s, sx, sy, filter, canvas, READ_BUDGET)
}
-fn resize_with_budget(s: &Surface, sx: f64, sy: f64, filter: Resample, edge: Option<Rect>, budget: usize) -> Surface {
+/// Runs `filter`'s passes. Between two passes the image is stored in its own format, which
+/// clips it (and rounds it at 8 and 16 bits) as Photoshop does; the smaller scale goes first, so
+/// the intermediate image is never larger than the result.
+fn resize_with_budget(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Option<Rect>, budget: usize) -> Surface {
+ let mut cur: Option<Surface> = None;
+ let mut canvas = canvas;
+ for p in plan(filter, sx, sy) {
+ let next = resize_pass(cur.as_ref().unwrap_or(s), p, canvas, budget);
+ canvas = canvas.map(|c| scaled_rect(c, p.sx, p.sy));
+ cur = Some(next);
+ }
+ let mut out = cur.unwrap_or_else(|| s.clone());
+ if filter == Resample::PreserveDetails && (sx > 1.0 || sy > 1.0) {
+ let dst = out.content_bounds();
+ let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 };
+ let area = crate::output_area(&p, dst, dst, None);
+ out = crate::apply(&out, &p, area, dst, None);
+ }
+ out.prune();
+ out
+}
+
+/// One pass. With `canvas`, the content and the canvas repeat their edge outwards (see
+/// [`resize_surface_in_canvas`]).
+fn resize_pass(s: &Surface, pass: Pass, canvas: Option<Rect>, budget: usize) -> Surface {
+ let Pass { sx, sy, kx, ky } = pass;
+ let edge = canvas.map(|c| s.content_bounds().union(&c)).filter(|a| !a.is_empty());
let fmt = s.format();
let mut out = Surface::with_default(fmt, &s.default_pixel());
let src = s.content_bounds();
@@ -199,8 +349,8 @@ fn resize_with_budget(s: &Surface, sx: f64, sy: f64, filter: Resample, edge: Opt
let alpha = fmt.alpha;
// With `edge`, every tap is clamped into the edge area, which holds the content.
let area = edge.unwrap_or(src);
- let hx = taps(dst.x0, dst.x1, sx, filter, edge.map(|r| (r.x0, r.x1 - 1)), (area.x0, area.x1 - 1));
- let vy = taps(dst.y0, dst.y1, sy, filter, edge.map(|r| (r.y0, r.y1 - 1)), (area.y0, area.y1 - 1));
+ let hx = taps(dst.x0, dst.x1, sx, kx, edge.map(|r| (r.x0, r.x1 - 1)), (area.x0, area.x1 - 1));
+ let vy = taps(dst.y0, dst.y1, sy, ky, edge.map(|r| (r.y0, r.y1 - 1)), (area.y0, area.y1 - 1));
let x_lo = hx.iter().filter(|t| !t.weights.is_empty()).map(|t| t.start).min().unwrap_or(area.x0);
let x_hi = hx.iter().map(|t| t.start + t.weights.len() as i32).max().unwrap_or(area.x0).max(x_lo);
let mut def = s.default_pixel();
@@ -312,12 +462,6 @@ fn resize_with_budget(s: &Surface, sx: f64, sy: f64, filter: Resample, edge: Opt
out.write_region(r, &d);
}
}
- if filter == Resample::PreserveDetails && (sx > 1.0 || sy > 1.0) {
- let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 };
- let area = crate::output_area(&p, out.content_bounds(), dst, None);
- out = crate::apply(&out, &p, area, dst, None);
- }
- out.prune();
out
}
@@ -353,7 +497,7 @@ mod tests {
fn fixed_channel_rows_match_dynamic_resampling() {
fn check<const N: usize>() {
for scale in [0.12, 0.5, 1.0, 2.3] {
- for filter in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] {
+ for filter in [Kernel::Nearest, Kernel::Bilinear, keys(Resample::Bicubic, scale), keys(Resample::BicubicSharper, scale), Kernel::Lanczos] {
for clamp in [None, Some((-3, 31))] {
let ts = taps(-5, 41, scale, filter, clamp, (-3, 31));
let row: Vec<f32> = (0..35 * N).map(|i| ((i * 73) % 251) as f32 / 250.0).collect();
@@ -374,6 +518,170 @@ mod tests {
check::<5>();
}
+ /// Photoshop 25.4's Image Size of a 16-bit greyscale pattern, in levels of 32768. Covers the
+ /// filters and their 2-D rules: Sharper reducing the width while the height grows is designed
+ /// for the height (not widened) and runs the width first; Bicubic Automatic splits a mixed
+ /// resize into Sharper and Smoother; Bicubic widens for the height's 0.6 while the width
+ /// grows; Smoother below ¼ averages down first; Bilinear below ½ averages whole pixels. On black
+ /// and white the overshoot is clipped between the passes, so their order shows.
+ #[test]
+ fn matches_photoshop_image_size() {
+ // (black and white pattern, filter, size, new size, Photoshop's levels)
+ type Probe = (bool, Resample, (i32, i32), (i32, i32), &'static [u16]);
+ let cases: [Probe; 9] = [
+ (
+ false,
+ Resample::BicubicSharper,
+ (12, 10),
+ (7, 16),
+ &[
+ 3777, 13165, 22219, 16176, 10460, 19488, 29643, 11249, 12634, 21696, 13330, 10319, 18965, 29120, 21280, 11204, 20279, 16184, 8200, 17548,
+ 27703, 21824, 10182, 19259, 26967, 5238, 16528, 26683, 17366, 8895, 17922, 32768, 2402, 15190, 25345, 17493, 7834, 16903, 31316, 1748,
+ 14172, 24326, 24718, 6368, 15746, 30390, 0, 13107, 23169, 31215, 4790, 14456, 27639, 5080, 11597, 21880, 29649, 3864, 13507, 24136, 20600,
+ 10264, 20931, 28009, 0, 12446, 21385, 28735, 8754, 19642, 26154, 4049, 10895, 20832, 23523, 7620, 18485, 23204, 20126, 8787, 19818, 21447,
+ 6173, 17467, 20390, 31862, 6616, 18480, 24094, 6500, 16129, 19749, 27472, 5810, 17460, 28281, 7655, 15108, 18394, 25515, 4427, 16043,
+ 28749, 7026, 13691, 17871, 24992, 3904, 15520, 27200, 6075, 13168,
+ ],
+ ),
+ (
+ false,
+ Resample::BicubicAutomatic,
+ (12, 10),
+ (7, 16),
+ &[
+ 4201, 12337, 27677, 15894, 4816, 20021, 29631, 10348, 9882, 27304, 14492, 3766, 19574, 29046, 18743, 5944, 25299, 16116, 4147, 17829,
+ 27787, 19399, 4206, 21790, 23748, 7966, 15117, 26569, 15941, 2695, 19445, 28341, 10104, 13050, 25465, 16251, 2613, 18023, 26770, 8432,
+ 11951, 24281, 22800, 7141, 15351, 24790, 5953, 11004, 23130, 28322, 10921, 12440, 24940, 9659, 9368, 22012, 27611, 10006, 10488, 26419,
+ 18657, 7071, 20807, 25492, 6937, 9239, 26574, 22363, 5435, 19688, 24808, 9136, 8184, 25295, 19708, 3939, 18677, 25053, 18234, 7120, 24061,
+ 17941, 2545, 17568, 24869, 23748, 6081, 21401, 21862, 6018, 15056, 23602, 22177, 4859, 17816, 28450, 11911, 11653, 22253, 20263, 3595,
+ 15790, 29734, 12969, 9683, 21668, 19678, 3010, 15424, 28429, 11728, 9300,
+ ],
+ ),
+ (
+ false,
+ Resample::Bicubic,
+ (12, 10),
+ (20, 6),
+ &[
+ 11517, 10000, 8617, 9364, 12272, 16362, 21396, 25508, 25506, 19474, 10887, 5289, 5842, 10286, 14986, 18566, 21910, 25511, 28611, 29922,
+ 24788, 17949, 8497, 4593, 7309, 12594, 17150, 20945, 24892, 26196, 22979, 16123, 9691, 7483, 10061, 14653, 18841, 22420, 25514, 26824,
+ 25702, 23396, 17586, 11378, 8127, 8882, 12310, 17039, 22345, 25871, 24700, 18125, 9951, 5493, 6802, 11215, 15576, 19259, 22384, 23694,
+ 26692, 26985, 22732, 14270, 6889, 4950, 8348, 13583, 17529, 21570, 25966, 27275, 22817, 14643, 8068, 6911, 10694, 15930, 19443, 20705,
+ 21499, 23413, 25601, 24336, 18665, 11686, 7800, 8947, 12974, 18067, 22707, 25285, 23077, 16645, 9789, 6586, 8147, 12329, 15935, 17465,
+ 17962, 20462, 24615, 25377, 20036, 11458, 5421, 5415, 9528, 14134, 17782, 22482, 26926, 27479, 21881, 13308, 7533, 7734, 11549, 13992,
+ ],
+ ),
+ (
+ false,
+ Resample::BicubicSmoother,
+ (40, 3),
+ (9, 3),
+ &[
+ 11315, 18740, 17475, 15974, 16503, 16042, 18215, 14712, 16238, 18482, 14351, 14664, 18012, 20260, 13338, 15511, 18468, 18275, 16790, 19168,
+ 14745, 14998, 20341, 18150, 13819, 16493, 16432,
+ ],
+ ),
+ (
+ false,
+ Resample::Bilinear,
+ (12, 10),
+ (5, 4),
+ &[11316, 14541, 17920, 10855, 24679, 19763, 9933, 23757, 6247, 20070, 25601, 5325, 19149, 17306, 15463, 20992, 16384, 14541, 23143, 10854],
+ ),
+ (
+ false,
+ Resample::Nearest,
+ (12, 10),
+ (7, 16),
+ &[
+ 1638, 12698, 23757, 3482, 9011, 20070, 31130, 1638, 12698, 23757, 3482, 9011, 20070, 31130, 31130, 10854, 21914, 1638, 7168, 18227, 29286,
+ 29286, 9011, 20070, 31130, 5325, 16384, 27443, 29286, 9011, 20070, 31130, 5325, 16384, 27443, 27443, 7168, 18227, 29286, 3482, 14541,
+ 25600, 25600, 5325, 16384, 27443, 1638, 12698, 23757, 25600, 5325, 16384, 27443, 1638, 12698, 23757, 23757, 3482, 14541, 25600, 31130,
+ 10854, 21914, 23757, 3482, 14541, 25600, 31130, 10854, 21914, 21914, 1638, 12698, 23757, 29286, 9011, 20070, 20070, 31130, 10854, 21914,
+ 27443, 7168, 18227, 20070, 31130, 10854, 21914, 27443, 7168, 18227, 18227, 29286, 9011, 20070, 25600, 5325, 16384, 16384, 27443, 7168,
+ 18227, 23757, 3482, 14541, 16384, 27443, 7168, 18227, 23757, 3482, 14541,
+ ],
+ ),
+ (
+ true,
+ Resample::Bicubic,
+ (12, 10),
+ (20, 6),
+ &[
+ 9960, 6313, 993, 0, 4525, 14807, 26472, 32768, 32768, 23510, 10514, 0, 0, 0, 10110, 22576, 31764, 32768, 32768, 32768, 26136, 18594, 6164,
+ 0, 0, 2565, 14499, 26983, 32768, 32768, 26358, 14709, 3969, 0, 0, 6602, 17734, 27952, 32768, 32768, 31590, 27808, 18307, 7429, 0, 0, 3712,
+ 14435, 26473, 32768, 31131, 20665, 7535, 0, 0, 2177, 13238, 25049, 32768, 32768, 32768, 32768, 26136, 14174, 2548, 0, 0, 6190, 18705,
+ 30273, 32768, 32768, 25517, 13238, 2177, 0, 0, 7250, 19418, 26624, 32768, 32768, 32768, 28203, 18522, 7200, 0, 0, 3285, 14794, 26862,
+ 32768, 29913, 19013, 6667, 0, 0, 4443, 14506, 20751, 17344, 23066, 31075, 32361, 23949, 10738, 0, 0, 0, 10110, 22657, 32768, 32768, 32768,
+ 22658, 10192, 1004, 0, 0, 0,
+ ],
+ ),
+ (
+ true,
+ Resample::BicubicSharper,
+ (12, 10),
+ (7, 16),
+ &[
+ 801, 3050, 32489, 16260, 0, 29819, 32767, 9161, 1781, 29578, 14350, 0, 32768, 32767, 21132, 0, 25409, 17862, 0, 26925, 32767, 22769, 0,
+ 24839, 27566, 0, 9397, 32768, 19813, 0, 27795, 32768, 0, 0, 32768, 20744, 0, 25797, 32768, 0, 0, 32768, 27555, 0, 11184, 32768, 0, 0,
+ 32768, 32768, 0, 0, 32768, 5110, 0, 30386, 32768, 0, 0, 32768, 20385, 0, 23267, 32768, 0, 0, 32768, 29130, 0, 19191, 32768, 2670, 0, 31290,
+ 25387, 0, 21263, 32767, 20198, 0, 21586, 24510, 0, 23714, 32768, 32768, 0, 14165, 27804, 1007, 14254, 32768, 30149, 0, 16077, 32112, 2886,
+ 1884, 21043, 29607, 0, 16384, 32768, 3566, 0, 12683, 29616, 0, 16384, 32768, 3196, 0,
+ ],
+ ),
+ (
+ true,
+ Resample::BicubicSharper,
+ (12, 10),
+ (20, 6),
+ &[
+ 9273, 5043, 0, 0, 2698, 14484, 28464, 32768, 32768, 24841, 10877, 0, 0, 0, 9684, 22346, 31492, 32768, 32768, 32768, 25960, 18430, 4978, 0,
+ 0, 977, 15047, 28475, 32768, 32768, 27939, 14157, 1813, 0, 0, 5296, 17828, 28439, 32768, 32768, 32768, 27849, 17576, 6209, 0, 0, 2169,
+ 15076, 28935, 32768, 32768, 22167, 7399, 0, 0, 211, 12977, 24638, 32768, 32768, 32768, 32768, 25960, 14244, 824, 0, 0, 5093, 18802, 31993,
+ 32768, 32768, 26467, 12977, 211, 0, 0, 6300, 19418, 26712, 32768, 32768, 32768, 27907, 17874, 5820, 0, 0, 1853, 16055, 29518, 32768, 32768,
+ 20889, 5880, 0, 0, 2879, 13798, 20185, 19010, 25565, 32768, 32302, 25431, 11478, 0, 0, 0, 9684, 23083, 32768, 32768, 32768, 23084, 10422,
+ 1276, 0, 0, 0,
+ ],
+ ),
+ ];
+ for (binary, filter, (w, h), (wo, ho), want) in cases {
+ let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::U16, false));
+ let canvas = Rect::new(0, 0, w, h);
+ let level = |x: i32, y: i32| match ((x * 37 + y * 101) % 17) as f32 {
+ k if binary => {
+ if k > 8.0 {
+ 32767.0 / 32768.0
+ } else {
+ 0.0
+ }
+ }
+ k => ((k / 16.0 * 0.9 + 0.05) * 32768.0).round() / 32768.0,
+ };
+ let px: Vec<f32> = (0..h).flat_map(|y| (0..w).map(move |x| level(x, y))).collect();
+ s.write_region(canvas, &px);
+ let o = resize_surface_in_canvas(&s, wo as f64 / w as f64, ho as f64 / h as f64, filter, canvas);
+ let got = o.read_region(Rect::new(0, 0, wo, ho));
+ assert_eq!(got.len(), want.len(), "{filter:?}");
+ let worst = got.iter().zip(want).map(|(g, &p)| (g * 32768.0 - p as f32).abs()).fold(0.0f32, f32::max);
+ assert!(worst <= 8.0, "{filter:?} {w}x{h} to {wo}x{ho}: {worst} levels of 32768 from Photoshop");
+ }
+ }
+
+ /// Photoshop's Bicubic doubles with the Keys cubic at a = −0.75 (Catmull-Rom is −0.5): an
+ /// impulse spreads as −9, −27, 67, 225 /256 and back, as Photoshop 25.4 gives it.
+ #[test]
+ fn bicubic_is_photoshops_keys_cubic() {
+ let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
+ let mut row = [0.25; 30];
+ row[10] = 0.75;
+ s.write_region(Rect::new(0, 0, 30, 1), &row);
+ let o = resize_surface(&s, 2.0, 1.0, Resample::Bicubic);
+ let got: Vec<f32> = o.read_region(Rect::new(17, 0, 25, 1)).iter().map(|v| (v - 0.25) * 512.0).collect();
+ for (g, want) in got.iter().zip([-9.0, -27.0, 67.0, 225.0, 225.0, 67.0, -27.0, -9.0]) {
+ assert!((g - want).abs() < 1e-3, "{got:?}");
+ }
+ }
+
#[test]
fn identity_scale_is_lossless() {
for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] {
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index a6096ac96..358b710e1 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -1396,7 +1396,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fit Image…",
&["File", "Automate"],
None,
- r##"{"width":px,"height":px,"dontEnlarge":bool=false,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails"="bicubic"}"##,
+ r##"{"width":px,"height":px,"dontEnlarge":bool=false,"resample":"automatic|preserveDetails|bicubicSmoother|bicubicSharper|bicubicAutomatic|bicubic|nearest|bilinear|lanczos"="bicubic"}"##,
has_doc,
fit_image
),
diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs
index 8ab6ad0ff..34ad2d6a5 100644
--- a/crates/engine/src/image_cmds.rs
+++ b/crates/engine/src/image_cmds.rs
@@ -131,11 +131,24 @@ pub(crate) fn scale_effects(fx: &mut Effects, k: f32) {
}
}
-fn parse_resample(s: &str) -> Option<Resample> {
- Some(match s {
- "none" => return None,
+/// Image Size's resampling methods; `None` changes the resolution only.
+#[derive(Clone, Copy)]
+enum Method {
+ None,
+ Filter(Resample),
+ /// Photoshop's Automatic: Preserve Details where the image grows, Bicubic Sharper otherwise.
+ Automatic,
+}
+
+fn parse_resample(s: &str) -> Method {
+ Method::Filter(match s {
+ "none" => return Method::None,
+ "automatic" => return Method::Automatic,
"nearest" | "nearestNeighbor" => Resample::Nearest,
"bilinear" => Resample::Bilinear,
+ "bicubicSmoother" => Resample::BicubicSmoother,
+ "bicubicSharper" => Resample::BicubicSharper,
+ "bicubicAutomatic" => Resample::BicubicAutomatic,
"lanczos" => Resample::Lanczos,
"preserveDetails" => Resample::PreserveDetails,
_ => Resample::Bicubic,
@@ -162,7 +175,7 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
let (nw, nh) = (nw.round().clamp(1.0, 300_000.0) as u32, nh.round().clamp(1.0, 300_000.0) as u32);
// Each side may reach 300000 px, but resampling writes real pixels: refuse a canvas whose
// raster alone would pass the budget, before allocating any of it (#1544).
- if resample.is_some() && (nw, nh) != (ow, oh) {
+ if !matches!(resample, Method::None) && (nw, nh) != (ow, oh) {
check_resample_budget("image.imageSize", &d.doc, nw, nh, ", or turn Resample off to change only the resolution")?;
}
let dpi = p.get("resolution").and_then(Value::as_f64).map(|v| v as f32);
@@ -170,7 +183,12 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(r) = dpi {
doc.resolution_dpi = r.clamp(1.0, 10_000.0);
}
- let Some(filter) = resample else { return Ok(()) };
+ let filter = match resample {
+ Method::None => return Ok(()),
+ Method::Filter(f) => f,
+ Method::Automatic if nw > ow || nh > oh => Resample::PreserveDetails,
+ Method::Automatic => Resample::BicubicSharper,
+ };
resample_doc(doc, nw, nh, filter);
Ok(())
})?;
@@ -462,7 +480,12 @@ fn crop_target(p: &Value) -> Result<CropTarget> {
};
let filter = match p.get("resample") {
None | Some(Value::Null) => Some(Resample::Bicubic),
- Some(v) => parse_resample(v.as_str().ok_or_else(|| bad(CMD, "`resample` must be a string"))?),
+ Some(v) => match parse_resample(v.as_str().ok_or_else(|| bad(CMD, "`resample` must be a string"))?) {
+ Method::None => None,
+ Method::Filter(f) => Some(f),
+ // The direction is known only once the frame is: bicubic's own automatic choice.
+ Method::Automatic => Some(Resample::BicubicAutomatic),
+ },
};
let filter = match (filter, size) {
(Some(f), _) => f,
@@ -639,7 +662,7 @@ pub fn specs() -> Vec<CommandSpec> {
"image.imageSize",
"Image Size…",
["Image"],
- r##"{"width":px,"height":px,"resolution":ppi,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails|none"="bicubic"} → {width,height} (the document's size after the command; "none" changes the resolution only)"##,
+ r##"{"width":px,"height":px,"resolution":ppi,"resample":"automatic|preserveDetails|bicubicSmoother|bicubicSharper|bicubicAutomatic|bicubic|nearest|bilinear|lanczos|none"="bicubic"} → {width,height} (the document's size after the command; "none" changes the resolution only)"##,
has_doc,
image_size
),
@@ -784,7 +807,7 @@ mod tests {
#[test]
fn image_size_scales_everything() {
- for resample in ["bicubic", "bilinear", "nearest", "lanczos", "preserveDetails"] {
+ for resample in ["bicubic", "bicubicSmoother", "bicubicSharper", "bicubicAutomatic", "automatic", "bilinear", "nearest", "lanczos", "preserveDetails"] {
let mut s = session();
s.execute("image.imageSize", json!({"width": 80, "resample": resample})).unwrap();
let d = doc(&s);
@@ -819,7 +842,15 @@ mod tests {
#[test]
fn image_size_keeps_canvas_edges_opaque() {
for depth in [8, 16, 32] {
- for (w, resample) in [(60, "bicubic"), (41, "lanczos"), (15, "bilinear"), (77, "preserveDetails")] {
+ for (w, resample) in [
+ (60, "bicubic"),
+ (41, "lanczos"),
+ (15, "bilinear"),
+ (77, "preserveDetails"),
+ (21, "bicubicSharper"),
+ (47, "automatic"),
+ (9, "bicubicAutomatic"),
+ ] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 30, "height": 20, "depth": depth, "background": "#336699"})).unwrap();
s.execute("select.all", json!({})).unwrap();
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index f04b62e06..4869d973b 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -856,6 +856,9 @@
Bend: Ohyb:
Bicubic Bikubická
Bicubic (smooth gradients) Bikubická (plynulé přechody)
+ Automatic Automaticky
+ Bicubic Smoother (enlargement) Bikubická hladší (zvětšení)
+ Bicubic Sharper (reduction) Bikubická ostřejší (zmenšení)
Bilinear Bilineární
Black Černá
Black & White Černobílá
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index e5180a8b3..53d331501 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -833,6 +833,9 @@
Bend: Biegung:
Bicubic Bikubisch
Bicubic (smooth gradients) Bikubisch (sanfte Verläufe)
+ Automatic Automatisch
+ Bicubic Smoother (enlargement) Bikubisch glatter (Vergrößerung)
+ Bicubic Sharper (reduction) Bikubisch schärfer (Verkleinerung)
Bilinear Bilinear
Black Schwarz
Black & White Schwarzweiß
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index 607740e67..15b6593b2 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -2038,6 +2038,8 @@
Bend: Καμπυλότητα:
Bicubic Δικυβικό
Bicubic (smooth gradients) Δικυβική (ομαλές διαβαθμίσεις)
+ Bicubic Smoother (enlargement) Δικυβική πιο ομαλή (μεγέθυνση)
+ Bicubic Sharper (reduction) Δικυβική πιο ευκρινής (σμίκρυνση)
Bilinear Διγραμμική
Black Point Compensation Αντιστάθμιση μαύρου σημείου
Black, White Μαύρο, λευκό
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 4e0480bca..f76770985 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -842,6 +842,9 @@
Bend: Curvatura:
Bicubic Bicúbica
Bicubic (smooth gradients) Bicúbica (degradados suaves)
+ Automatic Automático
+ Bicubic Smoother (enlargement) Bicúbica más suavizada (ampliación)
+ Bicubic Sharper (reduction) Bicúbica más enfocada (reducción)
Bilinear Bilineal
Black Negro
Black & White Blanco y negro
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index e07163142..33c9ad015 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -830,6 +830,9 @@
Bend: Courbure :
Bicubic Bicubique
Bicubic (smooth gradients) Bicubique (dégradés lisses)
+ Automatic Automatique
+ Bicubic Smoother (enlargement) Bicubique plus lisse (agrandissement)
+ Bicubic Sharper (reduction) Bicubique plus net (réduction)
Bilinear Bilinéaire
Black Noir
Black & White Noir et blanc
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 73c038e93..f182b0d42 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -824,6 +824,9 @@
Bend: Lengkung:
Bicubic Bicubic
Bicubic (smooth gradients) Bicubic (gradien halus)
+ Automatic Otomatis
+ Bicubic Smoother (enlargement) Bicubic lebih halus (pembesaran)
+ Bicubic Sharper (reduction) Bicubic lebih tajam (pengecilan)
Bilinear Bilinear
Black Hitam
Black & White Hitam & Putih
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index e1180f8cd..34ba59922 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -840,6 +840,9 @@
Bend: Curvatura:
Bicubic Bicubica
Bicubic (smooth gradients) Bicubica (sfumature morbide)
+ Automatic Automatico
+ Bicubic Smoother (enlargement) Bicubica più morbida (ingrandimento)
+ Bicubic Sharper (reduction) Bicubica più nitida (riduzione)
Bilinear Bilineare
Black Nero
Black & White Bianco e nero
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 1cb135875..260da8f73 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -843,6 +843,9 @@
Bend: 曲げ:
Bicubic バイキュービック
Bicubic (smooth gradients) バイキュービック(滑らかな階調)
+ Automatic 自動
+ Bicubic Smoother (enlargement) バイキュービック法 - 滑らか(拡大)
+ Bicubic Sharper (reduction) バイキュービック法 - シャープ(縮小)
Bilinear バイリニア
Black 黒
Black & White 白黒
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 2f6347d6c..7d159bb28 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -815,6 +815,9 @@
Bend: 구부림:
Bicubic 쌍입방
Bicubic (smooth gradients) 쌍입방(부드러운 그레이디언트)
+ Automatic 자동
+ Bicubic Smoother (enlargement) 쌍입방 더 부드럽게(확대)
+ Bicubic Sharper (reduction) 쌍입방 더 선명하게(축소)
Bilinear 쌍선형
Black 검정
Black & White 흑백
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index 713f935b4..16d31f534 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -824,6 +824,8 @@
Bend: Buiging:
Bicubic Bicubisch
Bicubic (smooth gradients) Bicubisch (vloeiende verlopen)
+ Bicubic Smoother (enlargement) Bicubisch vloeiender (vergroten)
+ Bicubic Sharper (reduction) Bicubisch scherper (verkleinen)
Bilinear Bilineair
Black Zwart
Black & White Zwart-wit
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index 335b8d069..ce187a37b 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -840,6 +840,9 @@
Bend: Zgięcie:
Bicubic Dwusześcienna
Bicubic (smooth gradients) Dwusześcienna (gładkie gradienty)
+ Automatic Automatycznie
+ Bicubic Smoother (enlargement) Dwusześcienna wygładzona (powiększanie)
+ Bicubic Sharper (reduction) Dwusześcienna wyostrzona (zmniejszanie)
Bilinear Dwuliniowa
Black Czarny
Black & White Czerń i biel
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index beea57d3c..252fe4c64 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -826,6 +826,9 @@
Bend: Curvatura:
Bicubic Bicúbica
Bicubic (smooth gradients) Bicúbica (degradês suaves)
+ Automatic Automático
+ Bicubic Smoother (enlargement) Bicúbica mais suave (ampliação)
+ Bicubic Sharper (reduction) Bicúbica mais nítida (redução)
Bilinear Bilinear
Black Preto
Black & White Preto e branco
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 3ec3ce023..ee4a1a522 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -1978,6 +1978,9 @@
Baseline Базовая линия
Bicubic Бикубическая
Bicubic (smooth gradients) Бикубическая (плавные градиенты)
+ Automatic Автоматически
+ Bicubic Smoother (enlargement) Бикубическая, глаже (увеличение)
+ Bicubic Sharper (reduction) Бикубическая, чётче (уменьшение)
Bilinear Билинейная
Black, White Чёрный, белый
Blue, Red, Yellow Синий, красный, жёлтый
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index e15aee93a..4d50b1c18 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -1958,6 +1958,9 @@
Baseline Базова лінія
Bicubic Бікубічна
Bicubic (smooth gradients) Бікубічна (плавні градієнти)
+ Automatic Автоматично
+ Bicubic Smoother (enlargement) Бікубічна, гладкіша (збільшення)
+ Bicubic Sharper (reduction) Бікубічна, чіткіша (зменшення)
Bilinear Білінійна
Black, White Чорний, білий
Blue, Red, Yellow Синій, червоний, жовтий
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 362c3c9d8..3116d73e6 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -844,6 +844,9 @@
Bend: 弯曲:
Bicubic 双三次
Bicubic (smooth gradients) 双三次(平滑渐变)
+ Automatic 自动
+ Bicubic Smoother (enlargement) 双三次(较平滑)(扩大)
+ Bicubic Sharper (reduction) 双三次(较锐利)(缩减)
Bilinear 双线性
Black 黑色
Black & White 黑白
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index e278e4550..89433e241 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -847,6 +847,9 @@
Bend: 彎曲:
Bicubic 雙三次
Bicubic (smooth gradients) 雙三次 (平滑漸層)
+ Automatic 自動
+ Bicubic Smoother (enlargement) 雙三次 (較平滑) (放大)
+ Bicubic Sharper (reduction) 雙三次 (較銳利) (縮小)
Bilinear 雙線性
Black 黑色
Black & White 黑白
diff --git a/crates/ui-egui/src/sizing.rs b/crates/ui-egui/src/sizing.rs
index f194cad33..1863e44c0 100644
--- a/crates/ui-egui/src/sizing.rs
+++ b/crates/ui-egui/src/sizing.rs
@@ -31,11 +31,13 @@ fn pref_unit(u: photocraft_engine::prefs::Unit) -> &'static str {
pub(crate) fn pref_resample(i: photocraft_engine::prefs::Interpolation) -> &'static str {
use photocraft_engine::prefs::Interpolation;
match i {
+ Interpolation::BicubicAutomatic => "automatic",
Interpolation::Nearest => "nearest",
Interpolation::Bilinear => "bilinear",
- Interpolation::BicubicSharper => "lanczos",
+ Interpolation::Bicubic => "bicubic",
+ Interpolation::BicubicSmoother => "bicubicSmoother",
+ Interpolation::BicubicSharper => "bicubicSharper",
Interpolation::PreserveDetails => "preserveDetails",
- _ => "bicubic",
}
}
const ANCHORS: [&str; 9] = ["topLeft", "top", "topRight", "left", "center", "right", "bottomLeft", "bottom", "bottomRight"];
@@ -65,6 +67,7 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
f.insert("__constrain".into(), json!(true));
f.insert("resolution".into(), json!(res));
f.insert("resample".into(), json!(resample));
+ f.insert("__resample".into(), json!(resample));
} else {
f.insert("relative".into(), json!(false));
f.insert("anchor".into(), json!("center"));
@@ -260,7 +263,9 @@ fn image_size(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
label(ui, "", 90.0);
let mut on = resampling;
if crate::widgets::checkbox(ui, &mut on, tl!("Resample")).changed() {
- f.insert("resample".into(), json!(if on { "bicubic" } else { "none" }));
+ // Back on, it takes the method it had when the dialog opened.
+ let method = f.get("__resample").cloned().unwrap_or_else(|| json!("bicubic"));
+ f.insert("resample".into(), if on { method } else { json!("none") });
if !on {
f.insert("width".into(), json!(ow));
f.insert("height".into(), json!(oh));
@@ -268,12 +273,16 @@ fn image_size(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
}
if resampling {
let mut cur = resample.clone();
+ // Photoshop's list, then Lanczos.
let opts = [
+ ("automatic".to_string(), tl!("Automatic")),
("preserveDetails".to_string(), tl!("Preserve Details")),
+ ("bicubicSmoother".to_string(), tl!("Bicubic Smoother (enlargement)")),
+ ("bicubicSharper".to_string(), tl!("Bicubic Sharper (reduction)")),
("bicubic".to_string(), tl!("Bicubic (smooth gradients)")),
- ("lanczos".to_string(), tl!("Lanczos (sharp)")),
- ("bilinear".to_string(), tl!("Bilinear")),
("nearest".to_string(), tl!("Nearest Neighbor (hard edges)")),
+ ("bilinear".to_string(), tl!("Bilinear")),
+ ("lanczos".to_string(), tl!("Lanczos (sharp)")),
];
if crate::widgets::dropdown(ui, "is-resample", &mut cur, &opts, 200.0) {
f.insert("resample".into(), json!(cur));
@@ -432,6 +441,29 @@ mod tests {
assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(120, 50));
}
+ /// The dialog starts on Preferences › General › Image Interpolation: Bicubic Automatic opens
+ /// as Automatic and the others as themselves (Bicubic Sharper used to open as Lanczos).
+ #[test]
+ fn resample_follows_the_interpolation_preference() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap();
+ for (pref, method) in
+ [("bicubicAutomatic", "automatic"), ("bicubicSharper", "bicubicSharper"), ("bicubicSmoother", "bicubicSmoother"), ("nearestNeighbor", "nearest")]
+ {
+ app.session.execute("prefs.set", json!({"path": "general.imageInterpolation", "value": pref})).unwrap();
+ let id = open(&mut app, "image.imageSize").unwrap();
+ let f = &app.ui.dialog_mut(id).unwrap().fields;
+ assert_eq!((f.get("resample"), f.get("__resample")), (Some(&json!(method)), Some(&json!(method))), "{pref}");
+ app.ui.close_dialog(id);
+ }
+ let id = open(&mut app, "image.imageSize").unwrap();
+ let d = app.ui.dialog_mut(id).unwrap();
+ d.fields.insert("width".into(), json!(50));
+ d.fields.insert("height".into(), json!(25));
+ crate::dialogs::confirm(&mut app, id).unwrap();
+ assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(50, 25));
+ }
+
/// #441: a typed zero width showed "0 px × 1 px" while OK resized to 1×1.
#[test]
fn typed_zero_width_shows_the_applied_size() {