Crop Image: a turned image is cropped at the resolution asked for

object.cropImage with ppi draws a turned or skewed image at that ppi
even when it is the image's own, instead of at the lower density of the
box around it, and a ppi over that whole box makes the new image too.
The raster size limit applies only when the crop is drawn or resampled,
so a straight cut at the image's own ppi is not refused.

The Crop Image tool's Apply sends a turned image's own resolution when
no other is set and it is within 1 to 2400 ppi, and crops over the
whole box when a resolution is chosen.
This commit is contained in:
dotCooCoo
2026-11-15 17:51:37 -08:00
parent 41651e1f72
commit 2559d09158
6 changed files with 85 additions and 12 deletions
+19 -7
View File
@@ -999,10 +999,11 @@ fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Op
Some((cut, im.xf * Affine::translate((f64::from(x0), f64::from(y0)))))
}
/// Crop Image's `ppi`: the resolution the cropped image is resampled to, in pixels per point, or `None` to keep
/// the image's own. Refuses a resolution that isn't a positive number or is above what the image allows: its own,
/// or 300 ppi for a linked image, within 1 to 2400 ppi as Rasterize's.
fn crop_resolution(p: &Value, im: &ImageObject) -> Result<Option<f64>> {
/// Crop Image's `ppi`: the resolution asked for, in pixels per point, and whether it keeps the image's pixels as
/// they are (its own, with square pixels); `None` for the image's own. Refuses a resolution that isn't a positive
/// number or is above what the image allows: its own, or 300 ppi for a linked image, within 1 to 2400 ppi as
/// Rasterize's.
fn crop_resolution(p: &Value, im: &ImageObject) -> Result<Option<(f64, bool)>> {
const C: &str = "object.cropImage";
let Some(ppi) = p.get("ppi").filter(|v| !v.is_null()) else { return Ok(None) };
let ppi = ppi.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| bad(C, format!("ppi must be a positive number, not {ppi}")))?;
@@ -1015,7 +1016,7 @@ fn crop_resolution(p: &Value, im: &ImageObject) -> Result<Option<f64>> {
return Err(bad(C, format!("ppi can't be more than {max} for this image")));
}
// An image whose pixels are not square is resampled on both sides, even at its denser side's resolution.
Ok((!vectorcraft_tools::cropimage::keeps_resolution(im, ppi, 1e-6)).then_some(ppi / 72.0))
Ok(Some((ppi / 72.0, vectorcraft_tools::cropimage::keeps_resolution(im, ppi, 1e-6))))
}
/// A `w` × `h` image resampled at a resolution asked for, held to the size a drawing may have ([`MAX_PIXELS`], and
@@ -1095,7 +1096,9 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
return trim_image(s, id, (**im).clone());
}
let ib = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?;
let target = crop_resolution(p, im)?;
let asked = crop_resolution(p, im)?;
// The resolution the image's pixels are resampled to when they are cut straight.
let target = asked.and_then(|(t, keeps)| (!keeps).then_some(t));
let rect = match p.get("rect").filter(|v| !v.is_null()) {
Some(Value::Array(a)) if a.len() == 4 => {
let v: Vec<f64> = a.iter().filter_map(Value::as_f64).collect();
@@ -1119,7 +1122,10 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
}
// A box over the whole image still resamples it to a new resolution.
let whole = (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6;
if whole && target.is_none() {
// A turned or skewed image is drawn, so a resolution asked for, even its own, still makes a new image.
let [_, xb, xc, _, _, _] = im.xf.as_coeffs();
let turned = xb.abs() > 1e-9 || xc.abs() > 1e-9;
if whole && target.is_none() && (asked.is_none() || !turned) {
return Err(bad(C, "nothing to crop"));
}
if let Some(t) = target {
@@ -1141,6 +1147,12 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
put_pixels(s, id, encode_png(&cut)?, cw, ch, xf)?;
return Ok(json!({ "id": id.0, "width": cw, "height": ch }));
}
// A drawn crop is made at a resolution asked for even when it is the image's own: the box of a
// turned or skewed image holds fewer of its pixels a point than the image does.
let target = asked.map(|(t, _)| t);
if let Some(t) = target {
check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?;
}
// Drawn at the image's pixel density, or for a resolution asked for at up to twice that (no more
// than the image's own, measured on its pixel grid however it is turned, nor past the size a
// drawing may have), and resampled to it.
+19
View File
@@ -1760,6 +1760,25 @@ fn crop_image_of_a_turned_image_resamples_its_drawing() {
assert!(close(c.x0, b.x0 + 40.0) && close(c.y0, b.y0 + 40.0) && close(c.width(), 72.0) && close(c.height(), 36.0), "{c:?}");
}
/// A turned image cropped at its own resolution, asked for, gets that resolution, not the lower
/// density of the box around it.
#[test]
fn crop_image_of_a_turned_image_at_its_own_resolution_keeps_it() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
s.execute("object.rotate", &json!({"angle": 45})).unwrap();
let b = bounds(&s, img);
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 36})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (36, 18), "{r}");
// Over the whole box around it, its own resolution draws it square to the page.
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
s.execute("object.rotate", &json!({"angle": 45})).unwrap();
let b = bounds(&s, img);
let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()], "ppi": 36})).unwrap();
assert_eq!(r["width"].as_u64().unwrap(), (b.width() / 2.0).round() as u64, "{r}");
let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()]}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}");
}
/// A linked image can be cropped to up to 300 ppi, even above its own; the crop embeds it.
#[test]
fn crop_image_takes_a_linked_image_up_to_300_ppi() {
+1 -1
View File
@@ -848,7 +848,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.cropImage",
"Crop Image",
"",
"{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error",
"{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set, and for a turned or skewed image its own when none is), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error",
),
("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"),
(
+41 -2
View File
@@ -213,9 +213,18 @@ impl CropImageTool {
let max = im.map_or(f64::INFINITY, |im| image_ppi(im).1);
// A resolution set before this image was selected is held to this image's limit.
let resample = ppi.map(|v| v.min(max)).filter(|v| im.is_none_or(|im| !keeps_resolution(im, *v, 1e-3)));
if !same(r, image) || resample.is_some() {
// A turned or skewed image is drawn to be cropped: the resolution goes with it even when
// it is the image's own, which the PPI field shows until another is chosen (when it is
// one `object.cropImage` takes). A resolution chosen for it crops even over the whole box.
let drawn = im.filter(|im| {
let [_, b, c, _, _, _] = im.xf.as_coeffs();
b.abs() > 1e-9 || c.abs() > 1e-9
});
let own = |im: &ImageObject| Some(image_ppi(im).0).filter(|v| (1.0..=2400.0).contains(v));
let send = resample.or_else(|| drawn.and_then(|im| ppi.or_else(|| own(im))).map(|v| v.min(max)));
if !same(r, image) || resample.is_some() || (drawn.is_some() && ppi.is_some()) {
let mut p = json!({ "rect": [r.x0, r.y0, r.width(), r.height()] });
if let Some(v) = resample {
if let Some(v) = send {
p["ppi"] = json!(v);
}
out.push(Action::Exec("object.cropImage".into(), p));
@@ -679,6 +688,36 @@ mod tests {
assert_eq!(exec(&enter(&mut t, &cx)), None, "held to its own over the whole image: nothing to do");
}
/// A turned image is drawn to be cropped, so Apply sends its own resolution too, the one the
/// PPI field shows, or the one chosen.
#[test]
fn apply_sends_a_turned_image_s_own_resolution() {
// Turned about the page's corner, it stays within the artboard.
let (mut d, s) = doc_with_image((150.0, 60.0));
let Some(id) = s.objects.first().copied() else { panic!("an image") };
if let Some(NodeKind::Image(im)) = d.node_mut(id).map(|n| &mut n.kind) {
im.xf = Affine::rotate(0.5) * im.xf;
}
let p = paint();
let cx = cx(&d, &s, &p);
let ppi = |acts: &[Action]| {
acts.iter().find_map(|a| match a {
Action::Exec(c, v) if c == "object.cropImage" => v.get("ppi").and_then(Value::as_f64),
_ => None,
})
};
let mut t = CropImageTool::default();
t.set_option("rect", &json!([150, 150, 20, 20]));
assert!(ppi(&enter(&mut t, &cx)).is_some_and(|v| (v - 36.0).abs() < 1e-9));
t.set_option("rect", &json!([150, 150, 20, 20]));
t.set_option("ppi", &json!(36));
assert!(ppi(&enter(&mut t, &cx)).is_some_and(|v| (v - 36.0).abs() < 1e-9));
// Over the whole box, Apply crops at a resolution chosen, and leaves it alone without one.
t.set_option("ppi", &json!(36));
assert!(ppi(&enter(&mut t, &cx)).is_some_and(|v| (v - 36.0).abs() < 1e-9));
assert!(!enter(&mut t, &cx).iter().any(|a| matches!(a, Action::Exec(..))));
}
/// A crop that fails leaves the tool chosen (the switch to the Selection tool is not made), so
/// the box and the resolution stay for another try; leaving the tool forgets them.
#[test]
+1 -1
View File
@@ -849,7 +849,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.cropImage",
"Crop Image",
"",
"{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error",
"{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set, and for a turned or skewed image its own when none is), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error",
),
("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"),
(
+4 -1
View File
@@ -1922,12 +1922,15 @@ missing one does.
`object.cropImage {ppi}` sets the cropped image's resolution in pixels per inch: the cut pixels are resampled to it,
and the image keeps the size of the crop box. A `rect` over the whole image with a new `ppi` only resamples the image.
An image scaled differently across and down is resampled on both sides, so its pixels come out square at `ppi`.
A turned or skewed image is drawn at the `ppi` given, even its own, and over the whole box around it as well; without
`ppi` it is drawn at the density of that box. The Crop Image tool's Apply sends such an image's own resolution when
no other is set, and crops it over the whole box only when a resolution is chosen.
The most it takes is the image's own resolution (along the denser side of its pixel grid, however it is turned), or
300 ppi for a linked image; above that it is refused with `ppi can't be more than {max} for this image`. A value
outside 1 to 2400 is refused with `ppi must be between 1 and 2400`, and a value that is not a positive number with
`ppi must be a positive number, not {ppi}`. A resample whose working copies would pass the raster allowance (2 GB,
512 MB in the web app) is refused with `an image of {w} × {h} pixels is too large to resample`, naming the size
of the pixels being resampled. A null `ppi` keeps the image's own, as a missing one does, and `ppi` with
of the pixels being resampled. A null `ppi` is read as a missing one, and `ppi` with
`trim` is refused. While the Crop Image tool is chosen, `tool.setOption` sets `ppi` (the resolution Apply sends),
`reference` (0 to 8, left to right and top to bottom: the point of the box that the Control bar's X and Y name and
that its W and H resize about; 4, the center, by default) and `linked` (W and H keep the box's proportions; false by