Render native XeTeX PNG, JPEG and BMP graphics
This commit is contained in:
1 parent
794c2f9b2c
commit
2bd6e19519
22 files changed
+821
-120
No files matched your search
@@ -0,0 +1,41 @@
|
||||
//! BMP raster decoding and the density recorded by the DIB header.
|
||||
use image::{ColorType, ImageDecoder, codecs::bmp::BmpDecoder};
|
||||
use std::io::Cursor;
|
||||
|
||||
use super::png::SampledImage;
|
||||
|
||||
pub(super) const SIGNATURE: &[u8] = b"BM";
|
||||
|
||||
pub(super) fn decode(bytes: &[u8]) -> Result<(SampledImage, [f64; 2]), String> {
|
||||
let dib = bytes.get(14..).ok_or("truncated BMP file header")?;
|
||||
let long = |at: usize| -> Result<u32, String> {
|
||||
let word = dib.get(at..at + 4).ok_or("truncated BMP DIB header")?;
|
||||
Ok(u32::from_le_bytes(word.try_into().unwrap()))
|
||||
};
|
||||
let density = match long(0)? {
|
||||
12 => [72.0; 2],
|
||||
40 | 52 | 56 | 108 | 124 => {
|
||||
let ppm = [long(24)? as i32, long(28)? as i32];
|
||||
if ppm.iter().all(|&value| value > 0) {
|
||||
ppm.map(|value| f64::from(value) * 0.0254)
|
||||
} else {
|
||||
[72.0; 2]
|
||||
}
|
||||
}
|
||||
_ => return Err("unsupported BMP DIB header".into()),
|
||||
};
|
||||
let decoder = BmpDecoder::new(Cursor::new(bytes)).map_err(|error| error.to_string())?;
|
||||
if decoder.color_type() != ColorType::Rgb8 {
|
||||
return Err("unsupported BMP color layout for XDV".into());
|
||||
}
|
||||
let (width, height) = decoder.dimensions();
|
||||
let capacity = decoder.total_bytes();
|
||||
if capacity > 256 * 1024 * 1024 {
|
||||
return Err("decoded BMP exceeds native image capacity".into());
|
||||
}
|
||||
let mut samples = vec![0; capacity as usize];
|
||||
decoder
|
||||
.read_image(&mut samples)
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok((SampledImage::rgb8([width, height], samples), density))
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//! ICC profile metadata needed by PDF image color spaces.
|
||||
|
||||
pub(super) fn intent(profile: &[u8], components: u8) -> Option<&'static str> {
|
||||
let header = profile.get(..128)?;
|
||||
let size = u32::from_be_bytes(header[..4].try_into().unwrap()) as usize;
|
||||
let signature: &[u8] = match components {
|
||||
1 => b"GRAY",
|
||||
3 => b"RGB ",
|
||||
4 => b"CMYK",
|
||||
_ => return None,
|
||||
};
|
||||
if size != profile.len() || &header[16..20] != signature || &header[36..40] != b"acsp" {
|
||||
return None;
|
||||
}
|
||||
let intent = u32::from_be_bytes(header[64..68].try_into().unwrap());
|
||||
[
|
||||
"Perceptual",
|
||||
"RelativeColorimetric",
|
||||
"Saturation",
|
||||
"AbsoluteColorimetric",
|
||||
]
|
||||
.get(intent as usize)
|
||||
.copied()
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! JPEG frame and density metadata. The encoded image stays in its original stream.
|
||||
//! JPEG frame, density and color-profile metadata.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub(super) const SIGNATURE: &[u8] = b"\xff\xd8";
|
||||
|
||||
@@ -7,7 +8,10 @@ pub(super) struct Header {
|
||||
pub precision: u8,
|
||||
pub components: u8,
|
||||
pub density: [u32; 2],
|
||||
pub xdv_density: [f64; 2],
|
||||
pub progressive: bool,
|
||||
pub icc: Option<Vec<u8>>,
|
||||
pub adobe: bool,
|
||||
}
|
||||
|
||||
pub(super) fn read(bytes: &[u8]) -> Result<Header, &'static str> {
|
||||
@@ -15,7 +19,10 @@ pub(super) fn read(bytes: &[u8]) -> Result<Header, &'static str> {
|
||||
.strip_prefix(SIGNATURE)
|
||||
.ok_or("missing JPEG signature")?;
|
||||
let mut density = [0, 0];
|
||||
let mut xdv_density = [0.0; 2];
|
||||
let mut first = true;
|
||||
let mut profile_chunks = BTreeMap::new();
|
||||
let mut adobe = false;
|
||||
let truncated = "premature end of JPEG header";
|
||||
loop {
|
||||
rest = rest.strip_prefix(&[0xff]).ok_or("expected JPEG marker")?;
|
||||
@@ -61,42 +68,87 @@ pub(super) fn read(bytes: &[u8]) -> Result<Header, &'static str> {
|
||||
precision,
|
||||
components,
|
||||
density,
|
||||
xdv_density: if xdv_density == [0.0; 2] {
|
||||
[72.0; 2]
|
||||
} else {
|
||||
xdv_density
|
||||
},
|
||||
progressive: marker == 0xc2,
|
||||
icc: assemble_profile(&profile_chunks),
|
||||
adobe,
|
||||
});
|
||||
}
|
||||
0xc5..=0xc7 | 0xc9..=0xcb | 0xcd..=0xcf => {
|
||||
return Err("unsupported JPEG compression");
|
||||
}
|
||||
0xe0 if first => {
|
||||
0xe0 => {
|
||||
if let Some(&[_, _, unit, x0, x1, y0, y1, ..]) = segment.strip_prefix(b"JFIF\0") {
|
||||
let x = u32::from(u16::from_be_bytes([x0, x1]));
|
||||
let y = u32::from(u16::from_be_bytes([y0, y1]));
|
||||
density = match unit {
|
||||
1 => [x, y],
|
||||
2 => [x * 254 / 100, y * 254 / 100],
|
||||
_ => [0, 0],
|
||||
xdv_density = match unit {
|
||||
1 => [f64::from(x), f64::from(y)],
|
||||
2 => [f64::from(x) * 2.54, f64::from(y) * 2.54],
|
||||
_ => [72.0; 2],
|
||||
};
|
||||
if density.contains(&0) {
|
||||
density = [density[0].max(density[1]); 2];
|
||||
if first {
|
||||
density = match unit {
|
||||
1 => [x, y],
|
||||
2 => [x * 254 / 100, y * 254 / 100],
|
||||
_ => [0, 0],
|
||||
};
|
||||
if density.contains(&0) {
|
||||
density = [density[0].max(density[1]); 2];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
0xe1 if first => {
|
||||
0xe1 => {
|
||||
if let Some(tiff) = segment.strip_prefix(b"Exif\0") {
|
||||
let start = tiff
|
||||
.iter()
|
||||
.position(|&byte| byte != 0)
|
||||
.unwrap_or(tiff.len());
|
||||
density = exif_density(&tiff[start..]).unwrap_or([0, 0]);
|
||||
if let Some((legacy, exact)) = exif_density(&tiff[start..]) {
|
||||
if first {
|
||||
density = legacy;
|
||||
}
|
||||
if xdv_density.iter().all(|dpi| *dpi < 0.1) {
|
||||
xdv_density = exact;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
0xe2 => {
|
||||
if let Some(&[index, count, ref bytes @ ..]) =
|
||||
segment.strip_prefix(b"ICC_PROFILE\0")
|
||||
{
|
||||
profile_chunks.insert(index, (count, bytes));
|
||||
}
|
||||
}
|
||||
0xee if segment.starts_with(b"Adobe") => adobe = true,
|
||||
_ => {}
|
||||
}
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
|
||||
fn exif_density(tiff: &[u8]) -> Option<[u32; 2]> {
|
||||
fn assemble_profile(chunks: &BTreeMap<u8, (u8, &[u8])>) -> Option<Vec<u8>> {
|
||||
let &(total, _) = chunks.get(&1)?;
|
||||
if usize::from(total) != chunks.len() {
|
||||
return None;
|
||||
}
|
||||
let mut profile = Vec::new();
|
||||
for index in 1..=total {
|
||||
let &(count, data) = chunks.get(&index)?;
|
||||
if count != total {
|
||||
return None;
|
||||
}
|
||||
profile.extend_from_slice(data);
|
||||
}
|
||||
Some(profile)
|
||||
}
|
||||
|
||||
fn exif_density(tiff: &[u8]) -> Option<([u32; 2], [f64; 2])> {
|
||||
let little = match tiff.get(..2)? {
|
||||
b"II" => true,
|
||||
b"MM" => false,
|
||||
@@ -127,6 +179,7 @@ fn exif_density(tiff: &[u8]) -> Option<[u32; 2]> {
|
||||
let end = start.checked_add(12 * entries)?;
|
||||
tiff.get(start..end)?;
|
||||
let mut density = [72, 72];
|
||||
let mut exact = [72.0; 2];
|
||||
let mut cm = false;
|
||||
for at in (start..end).step_by(12) {
|
||||
match (short(at)?, short(at + 2)?, long(at + 4)?) {
|
||||
@@ -135,7 +188,9 @@ fn exif_density(tiff: &[u8]) -> Option<[u32; 2]> {
|
||||
let numerator = long(offset)?;
|
||||
let denominator = long(offset.checked_add(4)?)?;
|
||||
if denominator != 0 {
|
||||
density[usize::from(tag == 283)] = numerator / denominator;
|
||||
let axis = usize::from(tag == 283);
|
||||
density[axis] = numerator / denominator;
|
||||
exact[axis] = f64::from(numerator) / f64::from(denominator);
|
||||
}
|
||||
}
|
||||
(296, 3, 1) => cm = short(at + 8)? == 3,
|
||||
@@ -145,6 +200,22 @@ fn exif_density(tiff: &[u8]) -> Option<[u32; 2]> {
|
||||
if cm {
|
||||
density =
|
||||
density.map(|value| u32::try_from(u64::from(value) * 254 / 100).unwrap_or(u32::MAX));
|
||||
exact = exact.map(|dpi| dpi * 2.54);
|
||||
}
|
||||
Some((density, exact))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::read;
|
||||
|
||||
#[test]
|
||||
fn jfif_keeps_fractional_xdv_density_and_legacy_integer_density() {
|
||||
let mut jpeg = b"\xff\xd8\xff\xe0\x00\x10JFIF\0\x01\x02\x02\x00\x30\x00\x39\0\0".to_vec();
|
||||
jpeg.extend_from_slice(b"\xff\xc0\x00\x0b\x08\x00\x64\x00\xb4\x01\x01\x11\x00");
|
||||
let header = read(&jpeg).unwrap();
|
||||
assert_eq!(header.size, [180, 100]);
|
||||
assert_eq!(header.density, [121, 144]);
|
||||
assert_eq!(header.xdv_density, [48.0 * 2.54, 57.0 * 2.54]);
|
||||
}
|
||||
Some(density)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! 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 ::png::{ColorType, Decoder, PixelDimensions, Transformations, Unit};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{fmt::Write, io::Cursor};
|
||||
|
||||
@@ -15,7 +15,7 @@ enum ColorSpace {
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub(super) struct PngImage {
|
||||
pub(super) struct SampledImage {
|
||||
pub(super) size: [u32; 2],
|
||||
pub(super) source_depth: u8,
|
||||
depth: u8,
|
||||
@@ -24,7 +24,7 @@ pub(super) struct PngImage {
|
||||
alpha: Vec<u8>,
|
||||
}
|
||||
|
||||
fn decode(bytes: &[u8]) -> Result<(PngImage, [u32; 2]), String> {
|
||||
pub(super) fn decode(bytes: &[u8]) -> Result<(SampledImage, Option<PixelDimensions>), String> {
|
||||
let read_info = |transforms| {
|
||||
let mut decoder = Decoder::new(Cursor::new(bytes));
|
||||
decoder.set_transformations(transforms);
|
||||
@@ -39,12 +39,9 @@ fn decode(bytes: &[u8]) -> Result<(PngImage, [u32; 2]), String> {
|
||||
reader = read_info(Transformations::EXPAND)?;
|
||||
}
|
||||
let info = reader.info();
|
||||
let density = info
|
||||
let physical = 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)
|
||||
});
|
||||
.filter(|physical| physical.unit == Unit::Meter);
|
||||
let palette = info.palette.clone();
|
||||
let capacity = reader
|
||||
.output_buffer_size()
|
||||
@@ -90,7 +87,7 @@ fn decode(bytes: &[u8]) -> Result<(PngImage, [u32; 2]), String> {
|
||||
buf.truncate(alpha.len() * color_bytes);
|
||||
}
|
||||
Ok((
|
||||
PngImage {
|
||||
SampledImage {
|
||||
size: [width, height],
|
||||
source_depth,
|
||||
depth,
|
||||
@@ -98,7 +95,7 @@ fn decode(bytes: &[u8]) -> Result<(PngImage, [u32; 2]), String> {
|
||||
samples: buf,
|
||||
alpha,
|
||||
},
|
||||
density,
|
||||
physical,
|
||||
))
|
||||
}
|
||||
|
||||
@@ -106,12 +103,15 @@ 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| {
|
||||
let (image, physical) = decode(&resource.data).map_err(|error| {
|
||||
format!(
|
||||
"could not parse PNG image {}: {error}",
|
||||
resource.version.path.display()
|
||||
)
|
||||
})?;
|
||||
let mut density = physical.map_or([0, 0], |physical| {
|
||||
[physical.xppu, physical.yppu].map(|px| ((u64::from(px) * 254 + 5_000) / 10_000) as u32)
|
||||
});
|
||||
let warning = if density.iter().any(|&dpi| dpi > 65_535) {
|
||||
Some("too large image resolution ignored")
|
||||
} else if density != [0, 0] && density.contains(&0) {
|
||||
@@ -141,7 +141,18 @@ pub(super) fn read(
|
||||
))
|
||||
}
|
||||
|
||||
impl PngImage {
|
||||
impl SampledImage {
|
||||
pub(super) fn rgb8(size: [u32; 2], samples: Vec<u8>) -> Self {
|
||||
Self {
|
||||
size,
|
||||
source_depth: 8,
|
||||
depth: 8,
|
||||
color: ColorSpace::Rgb,
|
||||
samples,
|
||||
alpha: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn has_alpha(&self, pdf_version: (i32, i32)) -> bool {
|
||||
pdf_version >= (1, 4) && !self.alpha.is_empty()
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user