From df730ecbcd8b0070d06e56b825c7616f015b3ffb Mon Sep 17 00:00:00 2001 From: yunustopalogullari-sudo <340302749+yunustopalogullari-sudo@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:21:39 +0100 Subject: [PATCH] PDF export: an image over 2^27 pixels is written scaled down instead of left out A placed image of more pixels than the writer is given (2^27) was left out of the PDF, with the warning for an image that can't be decoded (#10490). It is now decoded as Open and Place decode it, within MAX_RASTER_ALLOC and by the decoders that refuse a file too short for the pixels it declares, and scaled down to the most pixels that fit before the Compression and Output settings apply. The warning gives its size and the size written. An image that can't be scaled down (beyond the allowance, or CMYK) is still left out, and the warning gives its size as the cause. Co-Authored-By: Claude Fable 5.2 --- crates/pdf/src/export/exporter.rs | 12 +++ crates/pdf/src/export/images.rs | 17 ++-- crates/pdf/src/images.rs | 126 +++++++++++++++++++++++++--- crates/pdf/src/tests/cmykimages.rs | 3 +- crates/pdf/src/tests/compression.rs | 95 +++++++++++++++++++++ docs/mcp.md | 4 + 6 files changed, 238 insertions(+), 19 deletions(-) diff --git a/crates/pdf/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index c1fc8defe7..8fed06f86d 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -22,6 +22,18 @@ pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing /// 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 of `w` × `h` pixels, more than are written +/// ([`crate::images::MAX_EMBED_PIXELS`]), written scaled down to `nw` × `nh`. +pub(super) fn scaled_down((w, h): (u32, u32), (nw, nh): (u32, u32)) -> String { + format!("an image of {w} × {h} pixels is too large to write as it is: it is written at {nw} × {nh} pixels") +} + +/// The warning for an image of `w` × `h` pixels left out because it has more pixels than are +/// written ([`crate::images::MAX_EMBED_PIXELS`]) and couldn't be scaled down. +pub(super) fn too_large((w, h): (u32, u32)) -> String { + format!("an image of {w} × {h} pixels is too large to write 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 67f3a335ba..043c1119bc 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -1,4 +1,4 @@ -use super::exporter::{UNCONVERTED, UNDECODED, UNWRITABLE_IMAGE, q, writable, xf}; +use super::exporter::{UNCONVERTED, UNDECODED, UNWRITABLE_IMAGE, q, scaled_down, too_large, 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}; @@ -150,7 +150,9 @@ impl Exporter<'_> { /// 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`]; `None`, with /// [`UNCONVERTED`], for one whose colors the Output settings convert but that can only be - /// written in its own ([`crate::images::Recoded::unconverted`]). + /// written in its own ([`crate::images::Recoded::unconverted`]). An image of more pixels than + /// are written ([`crate::images::MAX_EMBED_PIXELS`]) is written scaled down, with + /// [`scaled_down`] among the warnings, and is `None`, with [`too_large`], when it can't be. 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; @@ -169,7 +171,9 @@ impl Exporter<'_> { let grey = out.converts_grey_images(); let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit, then, grey }); let mut unconverted = false; + let mut oversize = None; let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { + oversize = crate::images::oversize(&blob.bytes); let cmyk_image = blob.is_cmyk(); // RGB images of a CMYK document go to CMYK only with a CMYK destination; grey ones stay // grey ([`crate::images::recode`]). @@ -204,6 +208,9 @@ impl Exporter<'_> { }); if unconverted { self.warn(UNCONVERTED); + } else if let Some(source) = oversize { + // Its size is the cause, whether it is written smaller or left out. + self.warn(img.as_ref().map_or_else(|| too_large(source), |i| scaled_down(source, i.size()))); } else if img.is_none() { self.warn(UNDECODED); } @@ -428,9 +435,9 @@ pub(super) fn png_8_bit(bytes: &[u8]) -> Option> { /// image of 16 bits a sample is written at 8 bits ([`png_8_bit`]). pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool, profiles: SourceProfiles) -> Option { // The header's size first: the writer's decoders allocate what it declares, and the encoded - // bytes of an image that is far larger than any the app reads may be a few kilobytes. - let size = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions(); - if size.is_ok_and(|(w, h)| u64::from(w) * u64::from(h) > crate::images::MAX_EMBED_PIXELS) { + // bytes of an image that declares far more pixels than it holds may be a few kilobytes. One of + // more pixels than are written is not written as it is ([`crate::images::recode`] scales it down). + if crate::images::oversize(&blob.bytes).is_some() { return None; } let bytes = blob.bytes.as_ref().clone(); diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index bdf51da6f8..72d748a595 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -6,6 +6,8 @@ //! monochrome (greyscale that is only black and white). An image already as asked (not resampled, //! a JPEG kept as JPEG or another kept lossless) is embedded as it is; the others are decoded, //! resampled and encoded again. JPEG needs opaque pixels: images with transparency stay lossless. +//! An image of more pixels than are written ([`MAX_EMBED_PIXELS`]) is scaled down to that many +//! first, whatever the settings. //! A gray or RGB image that carries a profile the Output settings convert from ([`ToSrgb`]) is //! always decoded: its pixels are converted to sRGB and written without the profile, at 16 bits a //! sample when it has them and is otherwise kept as it is; a JPEG kept as JPEG whose samples the @@ -184,10 +186,79 @@ fn lossless( Image::from_custom(raw, interpolate).ok() } -/// Most pixels an image may have to be embedded: twice what the app reads (64 million), so every image -/// it holds is still written. +/// Most pixels an image is written with (134 million). The writer's decoders allocate what an +/// image's header declares, so one that declares more is not handed to them as it is: [`recode`] +/// writes it scaled down to this many ([`fit_size`]), and one that can't be scaled down is left +/// out. Open and Place hold larger images than this ([`vectorcraft_doc::MAX_RASTER_ALLOC`]). pub(crate) const MAX_EMBED_PIXELS: u64 = 1 << 27; +/// [`MAX_EMBED_PIXELS`], lowered by tests that need an image past it. +#[cfg(not(test))] +pub(crate) fn max_embed_pixels() -> u64 { + MAX_EMBED_PIXELS +} + +#[cfg(test)] +thread_local! { + pub(crate) static TEST_MAX_EMBED_PIXELS: std::cell::Cell = const { std::cell::Cell::new(MAX_EMBED_PIXELS) }; +} + +#[cfg(test)] +pub(crate) fn max_embed_pixels() -> u64 { + TEST_MAX_EMBED_PIXELS.with(std::cell::Cell::get) +} + +/// The size the header of image `bytes` declares, when it has more pixels than are written +/// ([`MAX_EMBED_PIXELS`]). `None` for a smaller image, and for a header that can't be read. +pub(crate) fn oversize(bytes: &[u8]) -> Option<(u32, u32)> { + let (w, h) = ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?; + (u64::from(w) * u64::from(h) > max_embed_pixels()).then_some((w, h)) +} + +/// The largest size of at most `max` pixels with the proportions of `w` × `h`, at least a pixel a +/// side: `w` × `h` itself when it has no more. +fn fit_size((w, h): (u32, u32), max: u64) -> (u32, u32) { + let pixels = u64::from(w) * u64::from(h); + if pixels <= max { + return (w, h); + } + let k = (max as f64 / pixels as f64).sqrt(); + let side = |n: u32| ((f64::from(n) * k).floor() as u32).clamp(1, n); + let (mut nw, mut nh) = (side(w), side(h)); + // A side held at a pixel leaves the other too long: cut to what fits. + if u64::from(nw) * u64::from(nh) > max { + let cut = |long: u32, short: u32| u32::try_from(max / u64::from(short)).unwrap_or(long).clamp(1, long); + if nw >= nh { + nw = cut(nw, nh); + } else { + nh = cut(nh, nw); + } + } + (nw, nh) +} + +/// Image `bytes`, whose header declares more pixels than are written ([`MAX_EMBED_PIXELS`]), +/// decoded as Open and Place decode it: within [`vectorcraft_doc::MAX_RASTER_ALLOC`], which the +/// header is checked against before any pixel is read, and by the decoders that refuse a file too +/// short to hold the pixels it declares, so a few kilobytes can't ask for the whole allowance. +/// `Err` as [`decoded_within`]'s: `true` for an image beyond the allowance (always on the web, +/// whose allowance is no more than the pixels written), `false` for one that can't be read. +fn decoded_oversize(bytes: &[u8]) -> Result { + match vectorcraft_doc::decode::decode_within(bytes, vectorcraft_doc::MAX_RASTER_ALLOC) { + Ok(Some((img, _))) => Ok(img), + Ok(None) => Err(true), + Err(_) => Err(false), + } +} + +/// `img` scaled down to the pixels that are written ([`fit_size`]), each new pixel the mean of +/// the old ones it covers ([`Resample::Average`]): filtered resampling would hold the whole image +/// again as floats. `img` itself when it has no more pixels than that. +fn fitted(img: DynamicImage) -> DynamicImage { + let (w, h) = fit_size((img.width(), img.height()), max_embed_pixels()); + resized(img, w, h, Resample::Average) +} + /// The most bytes an ICC profile carried by an image is written or read with (16 MiB). pub(crate) const MAX_ICC: usize = 16 << 20; @@ -551,7 +622,10 @@ pub(crate) fn is_grey(bytes: &[u8]) -> bool { /// gray or RGB profile other than sRGB are converted from it to sRGB instead ([`ToSrgb`]), and /// colour ones then by `convert`, or without it by the conversion `to_srgb` gives /// ([`ToSrgb::then`]); grey ones keep their profile unless the destination is sRGB -/// ([`ToSrgb::grey`]). `interpolate` lets viewers smooth it. An image that can't be decoded is +/// ([`ToSrgb::grey`]). `interpolate` lets viewers smooth it. An image of more pixels than are +/// written ([`MAX_EMBED_PIXELS`]) is never kept as it is: it is decoded as Open and Place decode it +/// ([`decoded_oversize`]) and scaled down to fit ([`fitted`]) before the settings apply, so its +/// resolution is the scaled pixels'. An image that can't be decoded is /// kept as it is, with a warning when its pixels were to be converted to sRGB. When `convert` /// was to convert its colors, it is [`Recoded::unconverted`] if its header can't be read (it may /// be in color) or its pixels are beyond the decode allowance; a color image whose pixel data @@ -569,7 +643,14 @@ pub(crate) fn recode( 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 }; - let dims = decoder.dimensions(); + let source_dims = decoder.dimensions(); + // An image of more pixels than are written is scaled down to fit before the settings apply. + let dims = fit_size(source_dims, max_embed_pixels()); + let oversize = dims != source_dims; + // Is the image already as `r` asks ([`kept`])? Never one that is scaled down to fit. + let kept = |r: &Rule| !oversize && kept(r, dims, size, jpeg); + // The pixels, within the allowance: of an image scaled down to fit, the one Open and Place have. + let read = || if oversize { decoded_oversize(bytes) } else { decoded_within(bytes) }; let grey = grey_type(decoder.original_color_type()); // Pixels in a profile they are converted from are decoded, whatever the Compression settings. // Grey pixels keep their profile unless the destination is sRGB ([`ToSrgb::grey`]). @@ -597,23 +678,25 @@ pub(crate) fn recode( let (mut 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 source.is_none() && kept(&g, dims, size, jpeg) && kept(&m, dims, size, jpeg) && g.instead == m.instead { + if source.is_none() && kept(&g) && kept(&m) && g.instead == m.instead { return Recoded { image: None, warning: g.instead, note: None, unconverted: false }; } // 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)) + let img = if oversize { read().ok() } else { DynamicImage::from_decoder(decoder).ok() }; + let Some(img) = img else { return Recoded { unconverted: false, ..keep } }; + // Scaling greys the edges of a black-and-white image: told apart before it. + (if bilevel(&img) { Kind::Mono } else { Kind::Gray }, Some(fitted(img))) } else { (Kind::Color, None) }; let mut rule = rule(c, kind); let convert = convert.filter(|_| kind == Kind::Color); - if kept(&rule, dims, size, jpeg) && convert.is_none() && source.is_none() { + if kept(&rule) && convert.is_none() && source.is_none() { return Recoded { image: None, warning: rule.instead, note: None, unconverted: false }; } // Pixels that can't be read can't be written in their own colors either; ones beyond the // allowance can. - let mut img = match pixels.map_or_else(|| decoded_within(bytes), Ok) { + let mut img = match pixels.map_or_else(|| read().map(fitted), Ok) { Ok(img) => img, Err(limited) => return Recoded { unconverted: limited && convert.is_some(), ..keep }, }; @@ -638,7 +721,7 @@ pub(crate) fn recode( } from_profile = true; // Written as it is only when nothing converts it further. - let as_is = kept(&rule, dims, size, jpeg) && convert.is_none() && then.is_none(); + let as_is = kept(&rule) && convert.is_none() && then.is_none(); // A JPEG kept as JPEG whose samples the conversion leaves unchanged (an sRGB // profile): its JPEG data, without the profile (and, with `Remove`, without its // segments: encoded again when those can't be taken out). @@ -657,7 +740,7 @@ pub(crate) fn recode( } srgb } - None => match decoded_within(bytes) { + None => match read().map(fitted) { Ok(img) => img, Err(limited) => return Recoded { unconverted: limited && convert.is_some(), ..keep }, }, @@ -751,11 +834,12 @@ pub(crate) fn recode_cmyk( let dims = ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok().and_then(|r| r.into_dimensions().ok()); // The JPEG data as it is (without its `ICC_PROFILE` segments with `CmykTag::Removed`: its // inks are encoded again when those can't be taken out), tagged with `icc` rather than - // with its own segments; one larger than [`MAX_EMBED_PIXELS`] is not written. + // with its own segments; one larger than [`MAX_EMBED_PIXELS`] is not written (its inks + // are beyond [`vectorcraft_doc::cmyk::MAX_CMYK_PIXELS`] too, so it can't be scaled down). if let Some((w, h)) = dims.filter(|d| kept(&rule, *d, size, true)) && let Some(data) = jpeg_data(&blob.bytes, tag == CmykTag::Removed) { - let image = (u64::from(w) * u64::from(h) <= MAX_EMBED_PIXELS) + let image = (u64::from(w) * u64::from(h) <= max_embed_pixels()) .then(|| Image::from_jpeg_with_icc(data.into(), icc.map(|i| i.to_vec().into()), interpolate).ok()) .flatten(); return Recoded { image, warning: rule.instead, note: None, unconverted: false }; @@ -903,6 +987,22 @@ fn to_jpeg(samples: &[u8], space: ImageColorspace, width: u32, height: u32, qual mod tests { use super::*; + /// The size an image is scaled down to has as many pixels as fit in its proportions; a line + /// of pixels longer than the limit is cut to it, and a side never goes below a pixel. + #[test] + fn fit_size_is_the_largest_size_in_proportion_within_the_limit() { + for ((w, h), max) in [((600u32, 600u32), 359_999), ((9921, 22677), MAX_EMBED_PIXELS)] { + let (nw, nh) = fit_size((w, h), max); + let (pixels, more) = (u64::from(nw) * u64::from(nh), u64::from(nw + 1) * u64::from(nh + 1)); + assert!(pixels <= max && more > max, "{w} × {h} in {max}: {nw} × {nh}"); + // In proportion, to the pixel each side is rounded down to. + assert!((u64::from(nw) * u64::from(h)).abs_diff(u64::from(nh) * u64::from(w)) < u64::from(w.max(h)), "{w} × {h}: {nw} × {nh}"); + } + assert_eq!(fit_size((30_000, 7), 1000), (1000, 1)); + assert_eq!(fit_size((7, 30_000), 1000), (1, 1000)); + assert_eq!(fit_size((600, 600), 360_000), (600, 600)); + } + /// The inks of a CMYK image with alpha, resampled, keep the amounts of the opaque pixels: the /// inks under the clear pixels beside them don't thin them out. #[test] diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index ef20585154..75472cc000 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -826,7 +826,8 @@ fn a_kept_cmyk_jpeg_declaring_too_many_pixels_is_left_out() { ] { let out = export_with_report(&d, &opts(s.clone())).unwrap(); assert!(written(&out.bytes).is_empty(), "{s}"); - assert!(out.warnings.iter().any(|w| w.contains("couldn't be decoded")), "{s}: {:?}", out.warnings); + // Its inks can't be read to scale it down: the warning gives its size as the cause. + assert!(out.warnings.iter().any(|w| w.contains("16384 × 16384") && w.contains("missing from the picture")), "{s}: {:?}", out.warnings); } } diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index f3fb0dc01d..05743f13b2 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -338,6 +338,101 @@ fn images_declaring_more_than_the_allowance_are_not_decoded() { assert!(r.image.is_none(), "kept as it is"); } +/// The export of `d` with `settings` (content streams left readable) while +/// [`crate::images::MAX_EMBED_PIXELS`] is lowered to `max` on this thread, so that a small image is +/// past it. +fn export_within(max: u64, d: &Document, settings: Value) -> ExportReport { + let mut settings: PdfSettings = serde_json::from_value(settings).unwrap(); + settings.compression.compress_text = false; + let old = crate::images::TEST_MAX_EMBED_PIXELS.replace(max); + let r = export_with_report(d, &PdfOptions { settings, ..Default::default() }); + crate::images::TEST_MAX_EMBED_PIXELS.set(old); + r.unwrap() +} + +/// The width and height of the first image in `pdf`. +fn image_size(pdf: &[u8]) -> (u32, u32) { + let text = String::from_utf8_lossy(pdf); + let after = |key: &str| text.split_once(key).map(|(_, rest)| rest.chars().take_while(char::is_ascii_digit).collect::()); + let side = |key: &str| after(key).and_then(|digits| digits.parse().ok()).unwrap_or_else(|| panic!("no {key}")); + (side("/Width "), side("/Height ")) +} + +/// An image of more pixels than are written is not left out: it is written with the most pixels +/// that fit, in its proportions and still compressed as its kind is (a JPEG stays a JPEG), and the +/// warning names its size and the size written. One of exactly that many is written as it is. +#[test] +fn an_image_of_more_pixels_than_are_written_is_scaled_down_to_fit() { + for (format, mime, filter) in [(ImageFormat::Png, "image/png", "FlateDecode"), (ImageFormat::Jpeg, "image/jpeg", "DCTDecode")] { + let d = doc(encoded(colour(), format), mime); + let r = export_within(600 * 600, &d, json!({})); + assert_eq!(image_size(&r.bytes), (600, 600), "{mime}, at the limit"); + assert!(r.warnings.is_empty(), "{mime}, at the limit: {:?}", r.warnings); + let max = 600 * 600 - 1; + let r = export_within(max, &d, json!({})); + let (w, h) = image_size(&r.bytes); + assert!(w == h && u64::from(w * h) <= max && u64::from((w + 1) * (h + 1)) > max, "{mime}: {w} × {h}"); + let images = image_spaces(&r.bytes); + assert!(images.len() == 1 && images[0].filter == filter, "{mime}: {images:?}"); + let named = r.warnings.len() == 1 && r.warnings[0].contains("600 × 600") && r.warnings[0].contains(&format!("{w} × {h}")); + assert!(named, "{mime}: {:?}", r.warnings); + } +} + +/// Each pixel of an image scaled down to fit is the mean of the pixels it covers: at a quarter of +/// its pixels, of each block of four. +#[test] +fn an_image_scaled_down_to_fit_averages_the_pixels_it_covers() { + let source = colour().to_rgb8(); + let r = export_within(300 * 300, &doc(encoded(colour(), ImageFormat::Png), "image/png"), json!({})); + let samples = image_samples(&r.bytes).into_iter().next().unwrap(); + let got = image::RgbImage::from_raw(300, 300, samples).expect("300 × 300 RGB samples"); + for (x, y, p) in got.enumerate_pixels() { + for c in 0..3 { + let sum: u32 = [(0, 0), (1, 0), (0, 1), (1, 1)].iter().map(|(dx, dy)| u32::from(source.get_pixel(2 * x + dx, 2 * y + dy)[c])).sum(); + assert!((u32::from(p[c]) * 4).abs_diff(sum) <= 4, "pixel {x}, {y}, channel {c}: {} for a sum of {sum}", p[c]); + } + } +} + +/// An image scaled down to fit is still what the settings make of it: a black-and-white one stays +/// black and white under the Monochrome settings, a colour one goes to the Output destination, and +/// the Compression settings resample the scaled pixels further. +#[test] +fn an_image_scaled_down_to_fit_follows_the_compression_and_output_settings() { + let bw = image::GrayImage::from_fn(600, 600, |x, y| image::Luma([if (x / 7 + y / 5) % 2 == 0 { 0 } else { 255 }])); + let bw = doc(encoded(bw.into(), ImageFormat::Png), "image/png"); + let r = export_within(300 * 300, &bw, json!({"compression": {"mono": {"compression": "ccittG4"}}})); + assert!(r.warnings.iter().any(|w| w.contains("CCITT")), "the Monochrome settings apply: {:?}", r.warnings); + let back = import(&r.bytes).unwrap(); + let got = image::load_from_memory(&back.images.values().next().unwrap().bytes).unwrap().to_luma8(); + assert!(got.dimensions() == (300, 300) && got.pixels().all(|p| p[0] == 0 || p[0] == 255), "black and white at 300 × 300"); + + let colour = doc(encoded(colour(), ImageFormat::Png), "image/png"); + let r = export_within(300 * 300, &colour, json!({"output": {"conversion": "destination", "destination": vectorcraft_color::cms::GENERIC_CMYK}})); + let images = image_spaces(&r.bytes); + assert!(images.len() == 1 && images[0].space == "DeviceCMYK", "converted to the destination: {images:?}"); + assert_eq!(image_size(&r.bytes), (300, 300)); + assert!(!r.warnings.iter().any(|w| w.contains("missing from the picture")), "{:?}", r.warnings); + + let r = export_within(300 * 300, &colour, json!({"compression": {"color": {"downsample": "average", "ppi": 100, "abovePpi": 150}}})); + assert_eq!(image_size(&r.bytes), (100, 100), "resampled to 100 ppi"); +} + +/// An image of more pixels than are written that can't be scaled down is left out, and the +/// warning gives its size as the cause: one whose pixels are beyond the allowance Open and Place +/// decode within, and one within it whose file is too short to hold the pixels its header +/// declares, which is refused before they are allocated. +#[test] +fn an_image_too_large_to_scale_down_is_left_out_with_its_size() { + for side in [60_000, 12_000] { + let (text, warnings) = pdf(&doc(declared_png(side, side), "image/png"), json!({})); + assert!(!text.contains("/Width "), "{side}"); + let named = warnings.len() == 1 && warnings[0].contains(&format!("{side} × {side}")) && warnings[0].contains("missing from the picture"); + assert!(named, "{side}: {warnings:?}"); + } +} + /// When the Output settings convert colors, a color image beyond the decode allowance can't be /// kept as it is: it is unconverted, and so is one whose header can't be read. A color image /// whose pixel data can't be read (tagged with an ICC profile it is converted from or not) can't diff --git a/docs/mcp.md b/docs/mcp.md index c3f1c89a91..e24cfab89c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1640,6 +1640,10 @@ Images follow the `compression` settings of their kind (`color`, `gray`, or `mon `abovePpi` as placed they are resampled (`downsample`: `average`, `subsample` or `bicubic`) to `ppi`, and compressed with `zip`, `jpeg` (at `quality`; images with transparency stay lossless) or `auto` (JPEGs stay JPEG, the others lossless). `none`, `jpeg2000`, CCITT and `runLength` are written as ZIP, with a warning when an image needs them. +An image of more than 2^27 pixels (134 million) is not written as it is: it is scaled down to the most pixels that +fit, in its proportions and each pixel the mean of those it covers, before those settings apply, and a warning gives +both sizes. One that can't be scaled down (its pixels are beyond what Open and Place decode, or it is a CMYK image) is +left out, and the warning gives its size. The pieces of an image bent by a Warp effect are resampled once, for the widest and the highest size any piece places the image at, and all paint that one image. A 16-bit PNG that is not resampled, recompressed or converted keeps its 16 bits a sample in PDF 1.5 and later files,