Merge pull request #8912 from dotCooCoo/fix/pdf-color-masked-cmyk-image-mask

PDF export: a color-masked CMYK image with an image mask keeps its hidden colors hidden
This commit is contained in:
BFlat authored and GitHub committed 2026-11-22 10:43:45 +07:00
commit f7bbafe13c
4 files changed
+93 -11

No files matched your search

+34 -10
View File
@@ -183,22 +183,33 @@ impl Exporter<'_> {
/// CMYK image `im` with the alpha of its opacity mask `m`, when the mask is a greyscale image
/// on the image's own pixel grid (an image's soft mask as it opens): the alpha is written as the
/// image's soft mask, as an RGBA image's is, rather than as a luminosity soft mask over it,
/// through which CoreGraphics draws CMYK images on black boxes (#2159). `None` for other
/// images and masks; cached like [`Self::load_image`], `interpolate` as there.
pub(super) fn masked_image(&mut self, im: &vectorcraft_doc::ImageObject, m: &vectorcraft_doc::OpacityMask, interpolate: bool) -> Option<Image> {
/// through which CoreGraphics draws CMYK images on black boxes (#2159). `shown` is `im` as it is
/// shown ([`vectorcraft_doc::Document::shown_image`]). When a color mask shows other pixels
/// that are not CMYK (`im`'s own pixels with the hidden colors clear), `im`'s inks are written
/// with the mask's alpha multiplied by the shown pixels' alpha, so the hidden colors stay
/// hidden; shown pixels that are CMYK are written themselves. `None` for other images and
/// masks, and for shown pixels of another size; cached like [`Self::load_image`],
/// `interpolate` as there.
pub(super) fn masked_image(
&mut self,
im: &vectorcraft_doc::ImageObject,
shown: &vectorcraft_doc::ImageObject,
m: &vectorcraft_doc::OpacityMask,
interpolate: bool,
) -> Option<Image> {
let art = &m.art;
let NodeKind::Image(mi) = &art.kind else { return None };
// A color-masked image in the mask's art masks with the pixels it shows.
let shown = self.doc.shown_image(art, mi);
let mi = &*shown;
let shown_mask = self.doc.shown_image(art, mi);
let mi = &*shown_mask;
let plain =
art.opacity >= 1.0 && art.blend == BlendMode::Normal && art.extras().mask.is_none() && !art.appearance.effects.iter().any(|e| e.visible);
if m.invert || !plain || (mi.xf, mi.width, mi.height) != (im.xf, im.width, im.height) {
return None;
}
let size = self.image_size(im);
let size = self.image_size(shown);
let interpolate = interpolate && self.interpolate;
let mut cache = format!("{}\u{0}{}\u{0}{}", im.key, mi.key, m.clip);
let mut cache = format!("{}\u{0}{}\u{0}{}\u{0}{}", im.key, shown.key, mi.key, m.clip);
if self.downsampled() {
cache.push_str(&format!("\u{0}{:.3}x{:.3}", size.0, size.1));
}
@@ -209,8 +220,20 @@ impl Exporter<'_> {
return i.clone();
}
let doc = self.doc;
let img = doc.image_blob(im).filter(|b| b.is_cmyk()).and_then(|blob| {
let alpha = crate::images::mask_alpha(doc.image_blob(mi)?, im.width, im.height, m.clip)?;
// Pixels a color mask shows that are not CMYK carry the hidden colors as their alpha.
let shown_blob = doc.image_blob(shown);
let (source, hidden) = match shown_blob {
Some(b) if shown.key != im.key && !b.is_cmyk() => (doc.image_blob(im), Some(b)),
b => (b, None),
};
let img = source.filter(|b| b.is_cmyk()).and_then(|blob| {
let mut alpha = crate::images::mask_alpha(doc.image_blob(mi)?, im.width, im.height, m.clip)?;
if let Some(hidden) = hidden {
let shown_alpha = crate::images::image_alpha(hidden, im.width, im.height)?;
for (a, s) in alpha.iter_mut().zip(shown_alpha) {
*a = ((u32::from(*a) * u32::from(s) + 127) / 255) as u8;
}
}
let icc = self.out.cmyk_image_icc(blob);
let tag = self.out.cmyk_tag(icc.as_deref());
let r = crate::images::recode_cmyk(blob, size, self.compression, interpolate, self.out.cmyk_pixels(), Some(alpha), tag);
@@ -452,7 +475,8 @@ mod tests {
assert!(exporter.colorized_image(&image("pic", scale), &paint, true).is_some(), "colorized at {scale}");
let art = vectorcraft_doc::Node::new(doc.layers[0].id, vectorcraft_doc::NodeKind::Image(Box::new(image("alpha", scale))));
let mask = vectorcraft_doc::OpacityMask::new(art, true);
assert!(exporter.masked_image(&image("inks", scale), &mask, true).is_some(), "masked at {scale}");
let inks = image("inks", scale);
assert!(exporter.masked_image(&inks, &inks, &mask, true).is_some(), "masked at {scale}");
}
assert_eq!(exporter.images.len(), 2, "{:?}", exporter.images.keys().collect::<Vec<_>>());
}
+5 -1
View File
@@ -375,7 +375,11 @@ impl Exporter<'_> {
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled);
let alpha = match (&n.kind, mask) {
// The mask's image shares the pixel grid only when it has the same corners (or none).
(NodeKind::Image(im), Some(m)) if n.image_quad() == m.art.image_quad() => self.masked_image(im, m, !n.extras().pixelated),
// A color-masked image keeps the colors it hides hidden.
(NodeKind::Image(im), Some(m)) if n.image_quad() == m.art.image_quad() => {
let shown = self.doc.shown_image(n, im);
self.masked_image(im, &shown, m, !n.extras().pixelated)
}
_ => None,
};
if let Some(m) = mask
+15
View File
@@ -840,6 +840,21 @@ pub(crate) fn mask_alpha(blob: &ImageBlob, width: u32, height: u32, clip: bool)
Some(img.pixels().map(|p| ((u32::from(p[0]) * u32::from(p[3]) + back * (255 - u32::from(p[3])) + 127) / 255) as u8).collect())
}
/// The alpha of each pixel of image `blob` (255 for an image without alpha), when it is `width` ×
/// `height` pixels. `None` for a CMYK image, another size, or one too large to hold as RGBA or
/// that can't be decoded; as in [`mask_alpha`], the size is read from the header first.
pub(crate) fn image_alpha(blob: &ImageBlob, width: u32, height: u32) -> Option<Vec<u8>> {
if blob.is_cmyk() {
return None;
}
let reader = ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?;
if reader.into_dimensions().ok()? != (width, height) || u64::from(width) * u64::from(height) * 4 > MAX_DECODE {
return None;
}
let img = decoded(&blob.bytes)?.into_rgba8();
(img.dimensions() == (width, height)).then(|| img.pixels().map(|p| p[3]).collect())
}
/// Opaque colour `samples` (grey, RGB, or CMYK ink amounts, as `space` says) as a JPEG at
/// `quality`, tagged with ICC profile `icc` when given. CMYK JPEGs hold Adobe's inverted samples,
/// which the PDF writer's Decode array undoes.
+39
View File
@@ -1210,6 +1210,45 @@ fn a_distorted_cmyk_image_and_its_grid_mask_with_the_same_corners_write_it_as_it
}
}
/// A color-masked CMYK image with a gray mask of its grid keeps its inks and its hidden colors
/// hidden: the image's `/SMask` is the mask's alpha times the alpha of the pixels the color mask
/// shows, so a hidden pixel stays clear where the mask's alpha is not zero, for a distorted image
/// too.
#[test]
fn a_color_masked_cmyk_image_with_a_grid_mask_keeps_its_hidden_colors_hidden() {
for distorted in [false, true] {
let mut d = masked_doc(png(image::GrayImage::from_raw(2, 2, vec![255, 128, 0, 64]).unwrap()), true, false);
// The first pixel hidden, where the mask is fully opaque, and the last half shown.
let alpha = [0, 255, 255, 128];
let shown = image::RgbaImage::from_fn(2, 2, |x, y| image::Rgba([0, 90, 200, alpha[(y * 2 + x) as usize]]));
d.images.insert("shown".into(), ImageBlob::new("image/png", png(shown)));
let id = d.layers[0].children().unwrap()[0].id;
let q = [(16.0, 0.0), (24.0, 0.0), (40.0, 40.0), (0.0, 40.0)].map(|(x, y)| Point::new(x, y));
let mut mask = d.node(id).unwrap().extras().mask.clone().unwrap();
if distorted {
Arc::make_mut(&mut mask.art).set_image_corners(q).unwrap();
}
let n = d.node_mut(id).unwrap();
n.extras_mut().mask = Some(mask);
n.extras_mut().color_mask = Some(Box::new(vectorcraft_doc::color_mask::ColorMask {
key: "shown".into(),
from: "img".into(),
background: vectorcraft_doc::color_mask::MaskBackground::Colors,
colors: vec![[255, 255, 255]],
contiguous: false,
measure: vectorcraft_doc::color_mask::MaskMatch::Distance,
tolerance: 0.0,
softness: 0.0,
}));
if distorted {
n.set_image_corners(q).unwrap();
}
let (bytes, smasks) = export_smasks(&d);
assert!(!smasks.is_empty() && smasks.iter().all(|m| m.as_deref() == Some(&[0, 128, 0, 32][..])), "{distorted}: {smasks:?}");
assert!(distorted || !String::from_utf8_lossy(&bytes).contains("/S/Luminosity"), "no luminosity soft mask");
}
}
/// A grey mask image with a color mask masks the CMYK image with the pixels it shows: its hidden
/// pixels are clear in the image's `/SMask`.
#[test]