From 119ce7942bd14467b9e870a43d3e69b82daa7482 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 18:42:17 -0800 Subject: [PATCH] PDF export: an image whose colors can't be converted is left out with a warning When the Output settings convert colors, an image whose pixels can't be decoded or written in the destination's colors was written as it was, in its own colors: a CMYK image with more pixels than CMYK inks are read for, or a color image the writer could embed but the decoder could not read. In PDF/X-1a that could also write a color space the standard forbids. Such an image is now left out with the warning "an image couldn't be converted to the Output destination and is missing from the picture". Gray images, whose pixels are not converted, and files that convert no colors keep the image as before. An image that can't be written at all still gets the warning that it couldn't be decoded. --- crates/engine/src/cmd/fileio/pdf.rs | 2 +- crates/pdf/src/export/exporter.rs | 4 +++ crates/pdf/src/export/images.rs | 17 ++++++++-- crates/pdf/src/images.rs | 48 +++++++++++++++++++---------- crates/pdf/src/tests/cmykimages.rs | 32 +++++++++++++++++++ crates/pdf/src/tests/compression.rs | 30 ++++++++++++++++++ docs/mcp.md | 4 ++- docs/target-app-parity.md | 1 + 8 files changed, 117 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index da6da069e9..affd39c416 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and one whose pixels can't be converted is left out with a warning; printer's marks are not converted), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", has_doc, export_pdf ), diff --git a/crates/pdf/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index f102e0a0ab..a116f8bc2a 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -18,6 +18,10 @@ pub(super) const MAX_PATTERN_DEPTH: u32 = 4; /// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; +/// The warning for an image left out because its colors can't be converted as the Output +/// settings ask, although it could be written in its own colors. +pub(super) const UNCONVERTED: &str = "an image couldn't be converted to the Output destination and is missing from the picture"; + /// The warning for an image whose placement cannot be written. pub(super) const UNWRITABLE_IMAGE: &str = "an image couldn't be written and is missing from the picture"; diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index af686e1857..19d4314553 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -1,4 +1,4 @@ -use super::exporter::{UNDECODED, UNWRITABLE_IMAGE, q, writable, xf}; +use super::exporter::{UNCONVERTED, UNDECODED, UNWRITABLE_IMAGE, q, writable, xf}; use super::{Arc, BlendMode, Color, Exporter, Image, Node, NodeKind, Paint, Rect, Size, Surface, cmyk, krilla}; use krilla::color::device_n::{Colorant, DeviceNSpace, Process}; use krilla::image::{BitsPerComponent, CustomImage, ImageColorspace}; @@ -124,7 +124,9 @@ impl Exporter<'_> { /// settings say ([`crate::images::recode`], [`crate::images::recode_cmyk`] for CMYK images); /// cached by key (and size when images are resampled). With `interpolate` (and the export's /// own setting), viewers may smooth it. `None`, with [`UNDECODED`] among the warnings, for an - /// image that is missing, can't be decoded or is in [`Self::left_out`]. + /// image that is missing, can't be decoded or is in [`Self::left_out`]; `None`, with + /// [`UNCONVERTED`], for one whose colors the Output settings convert but that can only be + /// written in its own ([`crate::images::Recoded::unconverted`]). fn load_image(&mut self, im: &vectorcraft_doc::ImageObject, size: (f64, f64), interpolate: bool) -> Option { let key = im.key.as_str(); let c = self.compression; @@ -139,6 +141,7 @@ impl Exporter<'_> { let doc = self.doc; let out = self.out.clone(); let profiles = !out.standard.cmyk_only(); + let mut unconverted = false; let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { @@ -153,9 +156,17 @@ impl Exporter<'_> { if let Some(w) = r.warning { self.warn(w); } + if r.unconverted { + // The source image would be written in its own colors: it is left out, with a + // warning that names the conversion when it could have been written. + unconverted = embed(blob, interpolate, self.sixteen_bit, profiles).is_some(); + return None; + } r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit, profiles)) }); - if img.is_none() { + if unconverted { + self.warn(UNCONVERTED); + } else if img.is_none() { self.warn(UNDECODED); } self.images.insert(cache, img.clone()); diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index 5204e4f396..90eca71f67 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -306,6 +306,9 @@ pub(crate) struct Recoded { pub image: Option, /// Set when the image isn't compressed as asked. pub warning: Option<&'static str>, + /// Set when the colors were to be converted but the image couldn't be decoded or written + /// with them: the source image, kept as it is, would be in its own colors. + pub unconverted: bool, } /// Is `img` (a grey image) only black and white? @@ -373,7 +376,9 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// resampled when its resolution is above the threshold, compressed with ZIP or JPEG, its colours /// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile /// they carry when `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces). -/// `interpolate` lets viewers smooth it. An image that can't be decoded is kept as it is. +/// `interpolate` lets viewers smooth it. An image that can't be decoded is kept as it is, and +/// is [`Recoded::unconverted`] when `convert` was to convert its colors (any image whose header +/// can't be read, as it may be in color). pub(crate) fn recode( bytes: &[u8], size: (f64, f64), @@ -382,24 +387,26 @@ pub(crate) fn recode( convert: Option<&Pixels>, profiles: bool, ) -> Recoded { - let keep = Recoded { image: None, warning: None }; + let keep = Recoded { image: None, warning: None, unconverted: convert.is_some() }; let Ok(reader) = ImageReader::new(Cursor::new(bytes)).with_guessed_format() else { return keep }; let jpeg = reader.format() == Some(ImageFormat::Jpeg); let Ok(mut decoder) = reader.into_decoder() else { return keep }; - // What the header declares is decoded within the image allowance, not whatever it asks for. - if decoder.set_limits(limits()).is_err() { - return keep; - } - let dims = decoder.dimensions(); use ExtendedColorType as T; let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); + // What the header declares is decoded within the image allowance, not whatever it asks for. + // Grey pixels aren't converted. + if decoder.set_limits(limits()).is_err() { + return Recoded { unconverted: convert.is_some() && !grey, ..keep }; + } + let dims = decoder.dimensions(); let (kind, pixels) = if grey { // Only the pixels tell monochrome images from greyscale ones: decoded unless both keep it. let (g, m) = (rule(c, Kind::Gray), rule(c, Kind::Mono)); if kept(&g, dims, size, jpeg) && kept(&m, dims, size, jpeg) && g.instead == m.instead { - return Recoded { image: None, warning: g.instead }; + return Recoded { image: None, warning: g.instead, unconverted: false }; } - let Ok(img) = DynamicImage::from_decoder(decoder) else { return keep }; + // Grey pixels aren't converted. + let Ok(img) = DynamicImage::from_decoder(decoder) else { return Recoded { unconverted: false, ..keep } }; (if bilevel(&img) { Kind::Mono } else { Kind::Gray }, Some(img)) } else { (Kind::Color, None) @@ -407,9 +414,9 @@ pub(crate) fn recode( let rule = rule(c, kind); let convert = convert.filter(|_| kind == Kind::Color); if kept(&rule, dims, size, jpeg) && convert.is_none() { - return Recoded { image: None, warning: rule.instead }; + return Recoded { image: None, warning: rule.instead, unconverted: false }; } - let Some(img) = pixels.or_else(|| decoded(bytes)) else { return keep }; + let Some(img) = pixels.or_else(|| decoded(bytes)) else { return Recoded { unconverted: convert.is_some(), ..keep } }; // Pixels that keep their colours keep the profile they are in; converted ones are in the // destination's. let want = if kind == Kind::Color { *b"RGB " } else { *b"GRAY" }; @@ -441,7 +448,8 @@ pub(crate) fn recode( to_jpeg(&samples, space, width, height, q, interpolate, icc.as_deref().map(Vec::as_slice)) }); let image = jpeg.or_else(|| from_rgba(rgba.as_raw(), width, height, interpolate, convert, icc)); - Recoded { image, warning: rule.instead } + let unconverted = image.is_none() && convert.is_some(); + Recoded { image, warning: rule.instead, unconverted } } /// A colorized image's coverage (one sample a pixel, `w` × `h`, see @@ -472,6 +480,7 @@ pub(crate) fn coverage_sized(w: u32, h: u32, cover: Vec, size: (f64, f64), c /// [`mask_alpha`]) the image is lossless and carries it as its soft mask; `None` then when its /// inks can't be read. When its numbers are kept, the image is tagged with CMYK profile `icc` /// (see [`cmyk_icc`]), and is untagged without one; converted pixels are never tagged with it. +/// With `convert`, an image whose inks can't be read or written is [`Recoded::unconverted`]. pub(crate) fn recode_cmyk( blob: &ImageBlob, size: (f64, f64), @@ -492,16 +501,22 @@ pub(crate) fn recode_cmyk( let image = (u64::from(w) * u64::from(h) <= MAX_EMBED_PIXELS) .then(|| Image::from_jpeg_with_icc(blob.bytes.as_ref().clone().into(), icc.map(|i| i.to_vec().into()), interpolate).ok()) .flatten(); - return Recoded { image, warning: rule.instead }; + return Recoded { image, warning: rule.instead, unconverted: false }; } } + // Inks that can't be read can't be converted: the image is not to be kept as it is. + let unconverted = Recoded { image: None, warning: None, unconverted: true }; let Some(inks) = blob.cmyk() else { - return Recoded { image: None, warning: Some(if jpeg { CMYK_KEPT } else { CMYK_RGB }) }; + if convert.is_some() { + return unconverted; + } + return Recoded { image: None, warning: Some(if jpeg { CMYK_KEPT } else { CMYK_RGB }), unconverted: false }; }; let (width, height) = sized(&rule, (inks.width, inks.height), size); let (inks, alpha) = match resampled_inks(inks, alpha, &rule, (width, height)) { Ok(r) => r, - Err(warning) => return Recoded { image: None, warning }, + Err(_) if convert.is_some() => return unconverted, + Err(warning) => return Recoded { image: None, warning, unconverted: false }, }; let (samples, space) = match convert { Some(p) => p.convert(&inks), @@ -510,7 +525,8 @@ pub(crate) fn recode_cmyk( // JPEG needs opaque pixels. let image = jpeg_quality(&rule, jpeg).filter(|_| alpha.is_none()).and_then(|q| to_jpeg(&samples, space, width, height, q, interpolate, icc)); let image = image.or_else(|| lossless(samples, alpha, space, width, height, interpolate, icc)); - Recoded { image, warning: rule.instead } + let unconverted = image.is_none() && convert.is_some(); + Recoded { image, warning: rule.instead, unconverted } } /// Ink amounts (four bytes a pixel) and their alpha (one byte a pixel), if any. diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 4719beec70..22b8636752 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -585,6 +585,38 @@ fn a_kept_cmyk_jpeg_declaring_too_many_pixels_is_left_out() { } } +/// A CMYK JPEG whose inks can't be read (it declares more pixels than CMYK images are decoded +/// with, though fewer than the writer embeds) is written with its own numbers only when they are +/// kept: when the Output settings convert its colors it is left out with a warning, in every +/// standard. +#[test] +fn a_cmyk_jpeg_whose_inks_cant_be_read_is_left_out_when_its_colors_are_converted() { + let mut jpg = cmyk_jpeg(&flat([0, 102, 255, 0], 4), 2, 2); + // Height and width of the SOF0 segment (after its marker, length and precision): 8200 × 8200. + let sof = jpg.windows(2).position(|w| w == [0xFF, 0xC0]).unwrap(); + jpg[sof + 5..sof + 9].copy_from_slice(&[0x20, 0x08, 0x20, 0x08]); + let blob = ImageBlob::new("image/jpeg", jpg); + assert!(blob.is_cmyk() && blob.cmyk().is_none()); + let d = image_doc(blob, 2, 2); + let out = export_with_report(&d, &opts(json!({}))).unwrap(); + let kept = written(&out.bytes); + assert!(kept.len() == 1 && kept[0].space == "DeviceCMYK", "kept as it is: {kept:?}"); + let unconverted = "an image couldn't be converted to the Output destination and is missing from the picture"; + for s in [ + json!({"output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + json!({"output": {"conversion": "destination", "destination": SRGB}}), + json!({"standard": "pdfX1a", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + json!({"standard": "pdfX4", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + json!({"standard": "pdfA2b", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + ] { + let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}")); + assert!(written(&out.bytes).is_empty(), "{s}"); + assert!(out.warnings.iter().any(|w| w == unconverted), "{s}: {:?}", out.warnings); + let other = out.warnings.iter().any(|w| w.contains("couldn't be decoded") || w.contains("written as it is")); + assert!(!other, "{s}: {:?}", out.warnings); + } +} + /// The profile each transparency group of written PDF `bytes` blends in: its ICC-based space's /// profile, or `None` for DeviceCMYK. fn group_profiles(bytes: &[u8]) -> Vec>> { diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index 400bc0b0a8..fafb642fbe 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -270,6 +270,36 @@ fn images_declaring_more_than_the_allowance_are_not_decoded() { assert!(r.image.is_none(), "kept as it is"); } +/// When the Output settings convert colors, a color image that can't be decoded can't be kept as +/// it is: it is unconverted, and so is one whose header can't be read. A grey one, whose pixels +/// aren't converted, and any image without a conversion are kept as they are. +#[test] +fn a_color_image_that_cant_be_decoded_for_a_conversion_is_unconverted() { + let d = doc(encoded(colour(), ImageFormat::Png), "image/png"); + let settings: PdfSettings = + serde_json::from_value(json!({"output": {"conversion": "destination", "destination": vectorcraft_color::cms::GENERIC_CMYK}})).unwrap(); + let out = crate::output::ColorOut::new(&d, &settings).unwrap(); + assert!(out.pixels().is_some()); + let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); + let cut = |img: DynamicImage| { + let mut png = encoded(img, ImageFormat::Png); + png.truncate(png.len() / 2); + png + }; + let cases = [ + ("RGB", cut(colour()), true), + ("unreadable", vec![1, 2, 3], true), + ("grey", cut(colour().grayscale()), false), + ("grey declaring more than the allowance", declared_png(60_000, 60_000), false), + ]; + for (what, bytes, unconverted) in cases { + let r = crate::images::recode(&bytes, (72.0, 72.0), &c, false, out.pixels(), true); + assert!(r.image.is_none(), "{what}"); + assert_eq!(r.unconverted, unconverted, "{what}"); + assert!(!crate::images::recode(&bytes, (72.0, 72.0), &c, false, None, true).unconverted, "{what}, no conversion"); + } +} + /// A version 2.1 display ICC profile for colour space `space` (`RGB ` or `GRAY`), `len` bytes in /// all, with an empty tag table, every byte after the tag count different from its neighbors. fn icc_profile(space: &[u8; 4], len: usize) -> Vec { diff --git a/docs/mcp.md b/docs/mcp.md index d4e03892e9..6028dbcb1e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5650,7 +5650,9 @@ the colour bars are process, spot and black-tint patches. Layers whose Print opt The Output and Advanced sections convert colours and write real text. `output: {conversion, destination}` converts every colour into the destination profile's model (`destination`; CMYK of another profile too) or only the colours of the other model (`preserveNumbers`: colours already in it keep their numbers); grey stays grey, images are converted -too and printer's marks are not. The destination is any profile `edit.colorSettings` lists (default: the document's +too and printer's marks are not. An image whose colors are to be converted but whose pixels can't be decoded or +written that way is left out with the warning "an image couldn't be converted to the Output destination and is +missing from the picture", rather than written in its own colors. The destination is any profile `edit.colorSettings` lists (default: the document's for its colour mode). `profiles` (`all`, `destination`, or `taggedSource` for a document assigned profiles with `edit.assignProfile`) writes colours in ICC-based spaces with their profiles embedded: CMYK with the destination's or the document's CMYK profile, RGB as sRGB, grey with the sRGB tone curve (PDF/A, PDF/X-3 and PDF/X-4 files are diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cad5851e98..b0a8cdfb52 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1864,6 +1864,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The pixels of a PNG, JPEG, GIF or WebP file that Place decodes to check them are kept in the image store the renderers share, so the canvas's first frame with the placed image draws them without decoding the file again on the UI thread: File › Place, a file dropped on the canvas, a click or drag of the place cursor, `file.place`, and Paste of such an image. A CMYK JPEG is still decoded when it is first drawn (`crates/ui-egui/src/placing.rs`, `crates/render/src/tests.rs`). - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). A quarter turn swaps the resolution's axes, so the image keeps its physical size. TIFFs read without the image decoder (grayscale with extra channels, CCITT Group 3, CMYK with one plane per ink) follow their Orientation tag too, and a turned CMYK JPEG or TIFF keeps its inks, at the 8 or 16 bits the file has, as a CMYK TIFF. - PDF export writes a CMYK image that keeps its numbers in an `ICCBased` color space holding, byte for byte, the CMYK profile the image carries (a CMYK TIFF's tag 34675, or a CMYK JPEG's `ICC_PROFILE` APP2 segments) when `output.profiles` is `all` or `taggedSource`, and in PDF/A-2b, PDF/X-3 and PDF/X-4 unless it is `destination` ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)). This covers a CMYK JPEG embedded as it is, one the Compression settings resample or compress again, a TIFF written again, and an image written with its mask as its soft mask. With `none`, and in PDF/X-1a, the image is DeviceCMYK and a JPEG's own profile is left out, so PDF/X-1a export writes a CMYK JPEG that carries a profile. Pixels the Output settings convert are never tagged with the profile of their old numbers. A profile tags an image only when its size, signature, class, CMYK color space and tag table are well formed and it is at most 16 MiB (VectorCraft's own limit). Transparency in a tagged CMYK document blends in the document's CMYK profile; when the file holds no space of that profile it blends in DeviceCMYK, or keeps its RGB space in PDF/A, and never in an image's own profile (`crates/pdf/src/tests/cmykimages.rs`, `export::writer::tests`). + - When the Output settings convert an image's colors ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)), PDF export leaves out an image whose pixels can't be decoded or written in the destination's colors, with the warning "an image couldn't be converted to the Output destination and is missing from the picture", in every standard, instead of writing it in its own colors. This covers a CMYK image with more than 2^26 pixels, the most VectorCraft reads CMYK inks for, and a color image that could be embedded as it is but can't be decoded. Gray images, whose pixels are not converted, and images in a file that converts no colors are written as before, and an image that can't be written at all still gets the warning that it couldn't be decoded (`crates/pdf/src/tests/cmykimages.rs`, `crates/pdf/src/tests/compression.rs`). - An image that Open and Place store again keeps the ICC profile its file embeds and its 16-bit samples. A turned PNG, JPEG, WebP or TIFF stored as PNG, and a TIFF the image decoder reads, keep their gray or RGB samples at 8 or 16 bits with their gray or RGB profile in the PNG's `iCCP` chunk ([PNG specification, iCCP](https://www.w3.org/TR/png-3/#11iCCP)). A CMYK TIFF stored with one plane per ink and a turned CMYK JPEG or TIFF keep their CMYK profile as TIFF tag 34675, a JPEG's put together from all its APP2 segments ([ICC image-format guide](https://github.com/InternationalColorConsortium/iccDEV/blob/master/iccdev-mcp/docs/icc-format-guide.md)). A profile whose color space differs from the stored samples' is left out. The profile is kept in the stored image; how CMYK inks are drawn and exported to PDF does not change (`crates/engine/src/cmd/fileio/tests.rs`). - PDF export writes a stored gray or RGB TIFF in an `ICCBased` color space that holds the gray or RGB profile of its tag 34675, at 16 bits a sample from PDF 1.5 on and 8 before, with its alpha as a soft mask only when some pixel is not opaque ([ISO 32000-1, §8.6.5.5](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=157)). A gray or RGB image, a PNG included, that the Compression settings resample or compress with JPEG keeps its profile too, and gray pixels in an RGB profile stay RGB. Pixels the Output settings convert, a profile whose color space differs from the samples', and a malformed profile, a PNG's or JPEG's kept as it is included, are written without it; such a JPEG keeps its JPEG data. PDF/X-1a allows no ICC-based color spaces, so there a gray image with a gray profile, kept as it is, resampled or compressed with JPEG, is written in DeviceGray without the profile, a JPEG kept as JPEG with its JPEG data unchanged, and RGB images are converted to CMYK as before. CMYK images are unchanged (`crates/pdf/src/tests/compression.rs`). - SVG import shows a raster `` whose EXIF orientation or TIFF Orientation tag turns or flips it upright, linked or as a data URL, and inside an SVG shown as an image: the pixels are stored turned, the width and height swap, and the `` box fits the turned image under `preserveAspectRatio`, as CSS `image-orientation: from-image` describes (). A turned CMYK JPEG or TIFF keeps its inks as a CMYK TIFF, as does a CMYK TIFF that is not turned. TIFF data URLs (`image/tiff`, or untyped TIFF bytes) are read, and TIFFs with an alpha or other extra channel, CCITT Group 3 TIFFs and CMYK TIFFs stored one plane per ink are read as Open and Place read them. The pixels are decoded within the decode allowance, and a TIFF claiming more strips or tiles than the decoder can count is refused before it is decoded (`crates/svg/tests/it/image_orientation.rs`).