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.
This commit is contained in:
dotCooCoo
2026-11-14 18:42:17 -08:00
parent 6016d6200f
commit 119ce7942b
8 changed files with 117 additions and 21 deletions
File diff suppressed because one or more lines are too long
+4
View File
@@ -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";
+14 -3
View File
@@ -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<Image> {
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());
+32 -16
View File
@@ -306,6 +306,9 @@ pub(crate) struct Recoded {
pub image: Option<Image>,
/// 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<u8>, 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.
+32
View File
@@ -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<Option<Vec<u8>>> {
+30
View File
@@ -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<u8> {
+3 -1
View File
@@ -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
+1
View File
@@ -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 `<image>` 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 `<image>` box fits the turned image under `preserveAspectRatio`, as CSS `image-orientation: from-image` describes (<https://www.w3.org/TR/css-images-3/#the-image-orientation>). 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`).