Import PNG images in the native PDF device

This commit is contained in:
gloamxun committed 2026-11-21 04:13:18 +08:00
1 parent 297431a547
commit 555a029505
13 files changed
+467 -35

No files matched your search

+204
View File
@@ -0,0 +1,204 @@
//! Decode PNG samples for native PDF image XObjects.
use super::{Part, PdfImage};
use crate::{pdf::objects, resources::LoadedResource};
use ::png::{ColorType, Decoder, Transformations, Unit};
use serde::{Deserialize, Serialize};
use std::{fmt::Write, io::Cursor};
pub(super) const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
enum ColorSpace {
Gray,
Rgb,
Indexed(Vec<u8>),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(super) struct PngImage {
pub(super) size: [u32; 2],
pub(super) source_depth: u8,
depth: u8,
color: ColorSpace,
samples: Vec<u8>,
alpha: Vec<u8>,
}
fn decode(bytes: &[u8]) -> Result<(PngImage, [u32; 2]), String> {
let read_info = |transforms| {
let mut decoder = Decoder::new(Cursor::new(bytes));
decoder.set_transformations(transforms);
decoder.set_ignore_text_chunk(true);
decoder.read_info().map_err(|error| error.to_string())
};
let mut reader = read_info(Transformations::IDENTITY)?;
let [width, height] = [reader.info().width, reader.info().height];
let source_depth = reader.info().bit_depth as u8;
// Preserve packed grayscale and palettes unless tRNS needs an alpha channel.
if reader.info().trns.is_some() {
reader = read_info(Transformations::EXPAND)?;
}
let info = reader.info();
let density = info
.pixel_dims
.filter(|physical| physical.unit == Unit::Meter)
.map_or([0, 0], |physical| {
[physical.xppu, physical.yppu].map(|px| ((u64::from(px) * 254 + 5_000) / 10_000) as u32)
});
let palette = info.palette.clone();
let capacity = reader
.output_buffer_size()
.ok_or("PNG dimensions exceed decoder capacity")?;
// The decoder limits its own scratch allocations. Its caller-provided
// output buffer also needs a bound before allocating decompressed pixels.
if capacity > 256 * 1024 * 1024 {
return Err("decoded PNG exceeds native image capacity".into());
}
let mut buf = vec![0; capacity];
let info = reader
.next_frame(&mut buf)
.map_err(|error| error.to_string())?;
if [info.width, info.height] != [width, height] {
return Err("PNG default frame dimensions differ from IHDR".into());
}
buf.truncate(info.buffer_size());
reader.finish().map_err(|error| error.to_string())?;
let color = match info.color_type {
ColorType::Grayscale | ColorType::GrayscaleAlpha => ColorSpace::Gray,
ColorType::Rgb | ColorType::Rgba => ColorSpace::Rgb,
ColorType::Indexed => {
let table = palette.ok_or("indexed PNG has no palette")?;
if !(3..=768).contains(&table.len()) || table.len() % 3 != 0 {
return Err("invalid indexed PNG palette".into());
}
ColorSpace::Indexed(table.into_owned())
}
};
let depth = info.bit_depth as u8;
let mut alpha = Vec::new();
if matches!(info.color_type, ColorType::GrayscaleAlpha | ColorType::Rgba) {
let sample = usize::from(depth / 8);
let stride = sample * info.color_type.samples();
let color_bytes = stride - sample;
alpha.reserve(buf.len() / stride);
for offset in (0..buf.len()).step_by(stride) {
let start = offset / stride * color_bytes;
// PDF's soft mask uses the high byte even for 16-bit PNG color.
alpha.push(buf[offset + color_bytes]);
buf.copy_within(offset..offset + color_bytes, start);
}
buf.truncate(alpha.len() * color_bytes);
}
Ok((
PngImage {
size: [width, height],
source_depth,
depth,
color,
samples: buf,
alpha,
},
density,
))
}
pub(super) fn read(
resource: LoadedResource,
fallback_resolution: i32,
) -> Result<(PdfImage, Option<&'static str>), String> {
let (image, mut density) = decode(&resource.data).map_err(|error| {
format!(
"could not parse PNG image {}: {error}",
resource.version.path.display()
)
})?;
let warning = if density.iter().any(|&dpi| dpi > 65_535) {
Some("too large image resolution ignored")
} else if density != [0, 0] && density.contains(&0) {
Some("too small image resolution ignored")
} else {
None
};
if warning.is_some() || density == [0, 0] {
let resolution = fallback_resolution.clamp(0, 65_535) as u32;
density = [if resolution == 0 { 72 } else { resolution }; 2];
}
let natural = std::array::from_fn(|axis| {
let numerator = 473_628_672_i64 * i64::from(image.size[axis]);
let denominator = 100 * i64::from(density[axis]);
(numerator + denominator / 2) / denominator
});
Ok((
PdfImage {
version: resource.version,
page: 1,
page_count: 1,
natural,
extent: [1.0_f64.to_bits(); 2],
objects: vec![vec![Part::Png(image)]],
},
warning,
))
}
impl PngImage {
pub(super) fn has_alpha(&self, pdf_version: (i32, i32)) -> bool {
pdf_version >= (1, 4) && !self.alpha.is_empty()
}
pub(super) fn append(
&self,
pdf: &mut Vec<Vec<u8>>,
attributes: &[u8],
compression: u8,
pdf_version: (i32, i32),
) -> usize {
let id = pdf.len() + 1;
let [width, height] = self.size;
let mut color = match &self.color {
ColorSpace::Gray => "/DeviceGray".to_owned(),
ColorSpace::Rgb => "/DeviceRGB".to_owned(),
ColorSpace::Indexed(table) => {
let mut color = format!("[/Indexed /DeviceRGB {} <", table.len() / 3 - 1);
for byte in table {
write!(color, "{byte:02X}").expect("writing to a string");
}
color.push_str(">]");
color
}
};
let has_alpha = self.has_alpha(pdf_version);
if has_alpha {
write!(color, " /SMask {} 0 R", id + 1).expect("writing to a string");
}
let strip_16 = pdf_version < (1, 5) && self.depth == 16;
let reduced;
let (depth, samples): (u8, &[u8]) = if strip_16 {
reduced = self.samples.iter().step_by(2).copied().collect::<Vec<_>>();
(8, &reduced)
} else {
(self.depth, &self.samples)
};
let extra = format!(
"/Type /XObject /Subtype /Image /Width {width} /Height {height} \
/ColorSpace {color} /BitsPerComponent {depth}"
);
let mut stream = objects::stream(&extra, samples, compression);
if !attributes.is_empty() {
// Image attributes are TeX printer bytes and may be non-UTF-8.
stream.splice(3..3, attributes.iter().copied().chain([b'\n']));
}
pdf.push(stream);
if has_alpha {
pdf.push(objects::stream(
&format!(
"/Type /XObject /Subtype /Image /Width {width} /Height {height} \
/ColorSpace /DeviceGray /BitsPerComponent 8"
),
&self.alpha,
compression,
));
}
id
}
}