lightweight_pdf/
images.rs1use lightweight_pdf_core::ImageFormat;
13use lightweight_pdf_writer::{ColorSpace, ImageDataFilter, PdfImage};
14
15#[derive(Debug)]
16pub enum ImageEmbedError {
17 PngFeatureDisabled,
20 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#[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_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 _ => Err(ImageEmbedError::DecodeFailed),
123 }
124}
125
126#[cfg(not(feature = "png"))]
127fn build_png(_bytes: &[u8]) -> Result<PdfImage, ImageEmbedError> {
128 Err(ImageEmbedError::PngFeatureDisabled)
129}