Skip to main content

lightweight_pdf/
images.rs

1//! Bridges validated `lightweight-pdf-core::Image` data to `lightweight-pdf-writer::PdfImage`
2//! (Phase 5, `plan/phases/phase-5-images.md` steps 2-3). JPEG passes
3//! through byte-for-byte as `DCTDecode` (`Image::new` already validated
4//! baseline-ness/color type in `lightweight-pdf-core`, no re-encoding). PNG is
5//! decoded — only PNG actually needs it, to split the alpha channel out
6//! into a separate `SMask` — via the feature-reduced, pure-Rust `png`
7//! crate (ADR-013); RGB/alpha pixels are then embedded *uncompressed*,
8//! consistent with content streams and embedded fonts elsewhere in V1
9//! (`plan/progress.md`: no Flate encoder implemented, so nothing here
10//! re-compresses either).
11
12use lightweight_pdf_core::ImageFormat;
13use lightweight_pdf_writer::{ColorSpace, ImageDataFilter, PdfImage};
14
15#[derive(Debug)]
16pub enum ImageEmbedError {
17    /// The document contains a PNG but the crate was built without the
18    /// `png` feature — there is no decoder available to split out alpha.
19    PngFeatureDisabled,
20    /// The `png` crate rejected the data at decode time (should be rare:
21    /// `lightweight-pdf-core::Image::new` already validated the header).
22    DecodeFailed,
23}
24
25impl core::fmt::Display for ImageEmbedError {
26    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
27        match self {
28            ImageEmbedError::PngFeatureDisabled => write!(f, "PNG image in document, but the `png` feature is disabled"),
29            ImageEmbedError::DecodeFailed => write!(f, "failed to decode PNG image data"),
30        }
31    }
32}
33
34/// Guards decompressed PNG output size (ADR-013: "Grenzen für ... dekomprimierte
35/// Bytes sind Pflicht") — generous but finite, enforced by the `png` crate
36/// itself via `Limits` during decode, not just this module's own pixel-count
37/// check in `lightweight-pdf-core`.
38#[cfg(feature = "png")]
39const MAX_DECOMPRESSED_BYTES: usize = 200_000_000;
40
41pub fn build_pdf_image(bytes: &[u8], format: ImageFormat, components: u8) -> Result<PdfImage, ImageEmbedError> {
42    match format {
43        ImageFormat::Jpeg => Ok(build_jpeg(bytes, components)),
44        ImageFormat::Png => build_png(bytes),
45    }
46}
47
48fn build_jpeg(bytes: &[u8], components: u8) -> PdfImage {
49    let color_space = if components == 1 {
50        ColorSpace::DeviceGray
51    } else {
52        ColorSpace::DeviceRgb
53    };
54    PdfImage {
55        // Width/Height are read from the same validated header
56        // `lightweight-pdf-core::Image` already parsed; re-deriving them from the
57        // JPEG SOF marker a second time here would just duplicate that
58        // parsing, so the facade takes them from the `RenderNode::Image`
59        // it's translating (see `render.rs`) and overwrites these
60        // placeholders before returning.
61        width_px: 0,
62        height_px: 0,
63        color_space,
64        bits_per_component: 8,
65        filter: ImageDataFilter::DctDecode,
66        data: bytes.to_vec(),
67        smask: None,
68    }
69}
70
71#[cfg(feature = "png")]
72fn build_png(bytes: &[u8]) -> Result<PdfImage, ImageEmbedError> {
73    let limits = png::Limits {
74        bytes: MAX_DECOMPRESSED_BYTES,
75    };
76    let decoder = png::Decoder::new_with_limits(std::io::Cursor::new(bytes), limits);
77    let mut reader = decoder.read_info().map_err(|_| ImageEmbedError::DecodeFailed)?;
78    let mut buf = vec![0u8; reader.output_buffer_size().ok_or(ImageEmbedError::DecodeFailed)?];
79    let info = reader.next_frame(&mut buf).map_err(|_| ImageEmbedError::DecodeFailed)?;
80    let pixels = &buf[..info.buffer_size()];
81
82    match info.color_type {
83        png::ColorType::Rgb => Ok(PdfImage {
84            width_px: info.width,
85            height_px: info.height,
86            color_space: ColorSpace::DeviceRgb,
87            bits_per_component: 8,
88            filter: ImageDataFilter::None,
89            data: pixels.to_vec(),
90            smask: None,
91        }),
92        png::ColorType::Rgba => {
93            let pixel_count = (info.width as usize) * (info.height as usize);
94            let mut rgb = Vec::with_capacity(pixel_count * 3);
95            let mut alpha = Vec::with_capacity(pixel_count);
96            for px in pixels.chunks_exact(4) {
97                rgb.extend_from_slice(&px[0..3]);
98                alpha.push(px[3]);
99            }
100            let smask = PdfImage {
101                width_px: info.width,
102                height_px: info.height,
103                color_space: ColorSpace::DeviceGray,
104                bits_per_component: 8,
105                filter: ImageDataFilter::None,
106                data: alpha,
107                smask: None,
108            };
109            Ok(PdfImage {
110                width_px: info.width,
111                height_px: info.height,
112                color_space: ColorSpace::DeviceRgb,
113                bits_per_component: 8,
114                filter: ImageDataFilter::None,
115                data: rgb,
116                smask: Some(Box::new(smask)),
117            })
118        }
119        // `lightweight-pdf-core::Image::new` only accepts color types 2 (RGB) and
120        // 6 (RGBA) — anything else reaching here would be a contract bug,
121        // not user input, but fail closed rather than embedding garbage.
122        _ => Err(ImageEmbedError::DecodeFailed),
123    }
124}
125
126#[cfg(not(feature = "png"))]
127fn build_png(_bytes: &[u8]) -> Result<PdfImage, ImageEmbedError> {
128    Err(ImageEmbedError::PngFeatureDisabled)
129}