From 540d7d9673f08aede73a2327ee098880c78a7b50 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 11:44:52 -0800 Subject: [PATCH] PDF/EPS/.ai import: store imported images with fast PNG compression Opening a PDF, EPS or .ai file with images re-encodes each image, and each image's opacity mask, as a PNG. Since the switch to the shared image codec these PNGs were written with the codec's default compression (deflate level 6) instead of fast compression. A PDF and an .ai file each holding one image opened about 50 ms and 105 ms slower than in 0.24.1. PDF import and the EPS and .ai readers now each encode through one helper that asks for PngCompression::Fast, the setting the SVG filter raster already uses. The pixels are unchanged. Tests check the zlib header of every PNG an import stores (RFC 1950 FLEVEL): PDF RGB, gray and image-mask images and a CMYK image's soft mask; a PostScript RGB image and a masked CMYK image's mask; and .ai RGB and Separation images with their masks, at full size and reduced. --- crates/eps/src/import.rs | 6 +++ crates/eps/src/import/ai/read/art.rs | 10 ++--- crates/eps/src/import/ai/tests.rs | 29 ++++++++++++++ crates/eps/src/import/data/ops.rs | 4 +- crates/eps/src/import/preview.rs | 2 +- crates/eps/src/import/tests.rs | 13 +++++++ crates/eps/src/import/tests_images.rs | 20 +++++++++- crates/pdf/src/import/builder.rs | 2 +- crates/pdf/src/import/state.rs | 12 ++++-- crates/pdf/src/tests/import_fidelity.rs | 52 ++++++++++++++++++++++++- 10 files changed, 136 insertions(+), 14 deletions(-) diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 6c85414463..db310e0f01 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -135,6 +135,12 @@ pub struct Imported { pub preview: bool, } +/// `img` as a PNG with fast compression, which keeps opening a file with large images quick. +pub(crate) fn png(img: &craft_image_codecs::Image) -> Option> { + let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() }; + craft_image_codecs::encode(img, craft_image_codecs::Format::Png, &opts).ok() +} + /// The DSC comments the reader uses. #[derive(Debug, Default, PartialEq)] struct Dsc { diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 95606c9ebb..e0a46fccb0 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -648,7 +648,7 @@ impl<'a> Reader<'a> { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; - let Ok(png) = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { + let Some(png) = crate::import::png(&img) else { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; @@ -678,7 +678,7 @@ impl<'a> Reader<'a> { } let written = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray) .ok() - .and_then(|img| craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()); + .and_then(|img| crate::import::png(&img)); let Some(png) = written else { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); @@ -778,7 +778,7 @@ impl<'a> Reader<'a> { }; craft_image_codecs::Image::from_raw(ow, oh, layout, craft_image_codecs::SampleType::U8, pixels) .ok() - .and_then(|img| craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()) + .and_then(|img| crate::import::png(&img)) .map(|png| ImageBlob::new("image/png", png)) }; // One that can't be encoded is left to the page's art, as one past the hard limits. @@ -870,7 +870,7 @@ impl<'a> Reader<'a> { let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, alpha.to_vec()) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = crate::import::png(&raw)?; let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); self.doc.images.entry(key.clone()).or_insert(blob); @@ -1224,7 +1224,7 @@ pub(super) fn preview_png(data: &[u8]) -> Option<(Vec, u32, u32)> { } let raw = craft_image_codecs::Image::from_raw(width, height, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = crate::import::png(&raw)?; Some((png, width, height)) } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 9ef4cbc840..fe425346d2 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -3154,6 +3154,35 @@ fn a_reduced_separation_image_keeps_its_ink_and_its_alpha_as_a_mask() { assert!(r.doc.images[&im.key].gray_source().is_some_and(|g| !g.alpha), "no alpha in the pixels"); } +/// Images come in as PNGs written with fast compression, which keeps a file with large images +/// quick to open: an RGB image with an alpha channel, and a Separation image with its opacity +/// mask, at full size and reduced to fit the limits. +#[test] +fn images_and_their_masks_are_stored_with_fast_compression() { + let pngs = |doc: &Document| { + let fast = |n: &Node| { + let NodeKind::Image(im) = &n.kind else { panic!("{:?}", n.kind) }; + let blob = &doc.images[&im.key]; + assert_eq!(blob.mime, "image/png"); + crate::import::tests::fastest_png(&blob.bytes) + }; + let a = art(doc); + let mut out = vec![fast(&a[0])]; + out.extend(a[0].extras().mask.as_ref().map(|m| fast(&m.art))); + out + }; + let rgb = image("[ 10 0 0 10 50 90 ]", (2, 1), ("DeviceRGB", 3, 1), &[255, 0, 0, 0, 255, 0, 255, 128], 10); + assert_eq!(pngs(&read(&rgb).unwrap().doc), [true], "the RGB image"); + let black = "1 [0 0 0 1 /DeviceCMYK (Black Ink) /Separation]"; + let ink = ink_image(black, 8, 1, 2, &[0, 255, 255, 64]); + assert_eq!(pngs(&read(&ink).unwrap().doc), [true, true], "the Separation image and its mask"); + let samples = [255u8; 16].iter().chain([0u8; 16].iter()).copied().collect::>(); + let ink = ink_image(black, 8, 1, 16, &samples); + let r = super::with_image_limits(4, 1 << 31, 512 << 20, || read(&ink).unwrap()); + assert!(r.warnings.iter().any(|w| w.contains("was reduced")), "{:?}", r.warnings); + assert_eq!(pngs(&r.doc), [true, true], "the reduced Separation image and its mask"); +} + #[test] fn images_with_alpha_channels() { // RGB samples, then the alpha channel (not counted in the data's size). diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index e9bf596eb3..c27dc3c3c6 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -1157,7 +1157,7 @@ impl Interp<'_> { else { return Ok(()); }; - let Ok(png) = craft_image_codecs::encode(&rgba, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { + let Some(png) = crate::import::png(&rgba) else { self.out.warn("an image that couldn't be read was left out"); return Ok(()); }; @@ -1184,7 +1184,7 @@ impl Interp<'_> { let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, alpha.to_vec()) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = crate::import::png(&raw)?; let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); self.out.doc.images.entry(key.clone()).or_insert(blob); diff --git a/crates/eps/src/import/preview.rs b/crates/eps/src/import/preview.rs index 36c0e5662c..87037fcd1a 100644 --- a/crates/eps/src/import/preview.rs +++ b/crates/eps/src/import/preview.rs @@ -46,7 +46,7 @@ fn image_doc(img: image::RgbaImage, frame: Rect) -> Option { } let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, img.into_raw()) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = super::png(&raw)?; let mut doc = Document::new(frame.width(), frame.height()); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 011cb86ce3..f920a1c364 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -208,6 +208,19 @@ fn arrays_and_dictionaries_holding_themselves_are_freed() { } } +/// Whether PNG `png` stores its pixels at the fastest level a zlib header names (RFC 1950 §2.2, +/// FLEVEL 0). +pub(super) fn fastest_png(png: &[u8]) -> bool { + let mut at = 8; + while let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) { + if kind == b"IDAT" { + return png.get(at + 9).is_some_and(|flg| flg >> 6 == 0); + } + at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize; + } + panic!("a PNG with image data: {png:?}"); +} + /// The objects of the document's layer. pub(super) fn objects(d: &Document) -> Vec> { d.layers[0].children().unwrap().clone() diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index e7fd734240..87a7560bfd 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -14,7 +14,7 @@ use vectorcraft_doc::cmyk::Inks; use vectorcraft_doc::{ImageBlob, Node, NodeKind}; use super::import; -use super::tests::{all, eps, read}; +use super::tests::{all, eps, fastest_png, read}; use super::tests_generators::pixel; /// Each pixel of the first image, row by row. @@ -223,6 +223,24 @@ fn masked_cmyk_images_keep_their_inks_and_carry_the_mask_as_an_opacity_mask() { assert!(first_image(&r).extras().mask.is_none()); } +/// Images come in as PNGs written with fast compression, which keeps a file with large images +/// quick to open: an RGB image, and the opacity mask of a masked CMYK image. +#[test] +fn images_and_their_masks_are_stored_with_fast_compression() { + let r = read("30 20 scale 3 2 8 [3 0 0 -2 0 2] <00ff00405060> <0000ff708090> true 3 colorimage"); + let b = blob(&r, &first_image(&r)); + assert_eq!(b.mime, "image/png"); + assert!(fastest_png(&b.bytes), "the RGB image"); + let r = read( + "/DeviceCMYK setcolorspace 30 20 scale << /ImageType 4 /Width 2 /Height 1 /BitsPerComponent 8 /Decode [0 1 0 1 0 1 0 1] \ + /ImageMatrix [2 0 0 -1 0 1] /DataSource <0a141e28 00667f08> /MaskColor [10 20 30 40] >> image", + ); + let n = first_image(&r); + let mask = blob(&r, &n.extras().mask.as_ref().expect("an opacity mask").art); + assert_eq!(mask.mime, "image/png"); + assert!(fastest_png(&mask.bytes), "the opacity mask"); +} + /// A CMYK JPEG gives its samples as stored, for the Decode array to read: Adobe's inverted /// samples with `[1 0 1 0 1 0 1 0]`, the ink amounts themselves with `[0 1 0 1 0 1 0 1]`. #[test] diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 0cfb8ea805..64da7fb8d5 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -1098,7 +1098,7 @@ impl<'p> Builder<'p> { a.data, ) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = super::state::png(&raw)?; let blob = ImageBlob::new("image/png", png); let k = blob.content_key(); self.images.insert(k.clone(), blob); diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index 629113680c..c85f36bd7f 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -378,19 +378,25 @@ pub(super) fn bounds(nodes: &[Arc]) -> Option { nodes.iter().try_fold(None, |acc, n| n.visual_bounds().map(|b| Some(acc.map_or(b, |a: Rect| a.union(b)))))? } +/// `img` as a PNG with fast compression, which keeps opening a file with large images quick. +pub(super) fn png(img: &craft_image_codecs::Image) -> Option> { + let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() }; + craft_image_codecs::encode(img, craft_image_codecs::Format::Png, &opts).ok() +} + pub(super) fn rgba_png(rgba: Vec, w: u32, h: u32) -> Option> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?; - craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() + png(&img) } pub(super) fn rgb_png(rgb: Vec, w: u32, h: u32) -> Option> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).ok()?; - craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() + png(&img) } pub(super) fn gray_png(gray: Vec, w: u32, h: u32) -> Option> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray).ok()?; - craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() + png(&img) } pub(super) fn resize_alpha(a: &LumaData, w: u32, h: u32) -> Vec { diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 5fdafeb5fc..731f18ff06 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, Knockout, LineCap, LineJoin, Node, NodeId, NodeKind, OpacityMask}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, ImageBlob, Knockout, LineCap, LineJoin, Node, NodeId, NodeKind, OpacityMask}; use vectorcraft_geom::{Rect, shapes}; use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; @@ -147,6 +147,56 @@ fn a_luminosity_soft_mask_of_an_image_keeps_the_images_colour() { assert_eq!(mask_image_pixels("Luminosity"), [[0, 0, 0, 255], [0, 0, 0, 0]]); } +/// Whether PNG `png` stores its pixels at the fastest level a zlib header names (RFC 1950 §2.2, +/// FLEVEL 0). +fn fastest_png(png: &[u8]) -> bool { + let mut at = 8; + while let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) { + if kind == b"IDAT" { + return png.get(at + 9).is_some_and(|flg| flg >> 6 == 0); + } + at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize; + } + panic!("a PNG with image data: {png:?}"); +} + +/// Images come in as PNGs written with fast compression, which keeps a file with large images +/// quick to open: an RGB image with a soft mask, the soft mask of a CMYK image as its opacity +/// mask, a gray image and an image mask painted in a color. +#[test] +fn imported_images_are_stored_with_fast_compression() { + let g = first_extra(1); + let image = |space: &str, data: &str| { + stream( + &format!( + "/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /{space} /BitsPerComponent 8 /Filter /ASCIIHexDecode /SMask {} 0 R", + g + 4 + ), + data, + ) + }; + let rgb = image("DeviceRGB", "FF000000FF00>"); + let cmyk = image("DeviceCMYK", "0A141E28 00667F08>"); + let gray = + stream("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /ASCIIHexDecode", "2080>"); + let stencil = stream("/Type /XObject /Subtype /Image /Width 8 /Height 1 /ImageMask true /BitsPerComponent 1 /Filter /ASCIIHexDecode", "F0>"); + let smask = + stream("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /ASCIIHexDecode", "FF40>"); + let bytes = one_page( + "q 40 0 0 40 0 0 cm /Im0 Do Q q 40 0 0 40 50 0 cm /Im1 Do Q q 40 0 0 40 0 50 cm /Im2 Do Q 0 0 1 rg q 40 0 0 40 50 50 cm /Im3 Do Q", + &format!("/XObject << /Im0 {g} 0 R /Im1 {} 0 R /Im2 {} 0 R /Im3 {} 0 R >>", g + 1, g + 2, g + 3), + &[&rgb, &cmyk, &gray, &stencil, &smask], + ); + let d = open(&bytes); + let masks = all(&d).iter().filter(|n| n.extras().mask.is_some()).count(); + assert_eq!(masks, 1, "the CMYK image's soft mask as an opacity mask"); + let pngs: Vec<&ImageBlob> = d.images.values().filter(|b| b.mime == "image/png").collect(); + assert_eq!(pngs.len(), 4, "the RGB image, the CMYK image's mask, the gray image and the image mask: {:?}", d.images.keys()); + for b in pngs { + assert!(fastest_png(&b.bytes), "{:?}", &b.bytes[..b.bytes.len().min(48)]); + } +} + #[test] fn a_luminosity_soft_mask_becomes_an_opacity_mask() { let d = open(&masked("/S /Luminosity", "1 1 1 rg 0 0 50 100 re f"));