1use pdf2::{Dictionary, Document, Object, Stream};
4
5use crate::canvas::{BlendMode, Canvas, ClipMask, Color};
6use crate::geom::{Matrix, Point};
7use crate::{Error, Result};
8
9#[derive(Debug, Clone)]
11pub struct Image {
12 width: u32,
13 height: u32,
14 pixels: Vec<Color>,
15 interpolate: bool,
16 masked: Option<Vec<bool>>,
18}
19
20impl Image {
21 pub fn from_stream(
27 document: &Document,
28 stream: &Stream,
29 id: Option<pdf2::ObjectId>,
30 ) -> Result<Self> {
31 let dict = stream.dict();
32 let width = integer(dict, b"Width")?;
33 let height = integer(dict, b"Height")?;
34 if width == 0 || height == 0 {
35 return Err(Error::malformed("image with zero width or height"));
36 }
37 let bits = dict
38 .get(b"BitsPerComponent")
39 .and_then(Object::as_integer)
40 .unwrap_or(8);
41 if bits != 8 && bits != 1 {
44 return Err(Error::malformed(
45 "only 1 and 8 bits per component images are rendered",
46 ));
47 }
48 let interpolate = matches!(dict.get(b"Interpolate"), Some(Object::Boolean(true)));
49 let space = resolve(document, dict.get(b"ColorSpace"))?;
50 let colours = ColourSpace::from_object(document, space)?;
56 let per_pixel = colours.components();
57 let count = (width as usize)
58 .checked_mul(height as usize)
59 .and_then(|pixels| pixels.checked_mul(per_pixel))
60 .ok_or_else(|| Error::malformed("image dimensions overflow"))?;
61 let limit = document.decoded_limit();
62 if count > limit {
63 return Err(Error::Limit {
64 what: "an image of the /Width and /Height it declares",
65 limit,
66 });
67 }
68 let key = match dict.get(b"Mask") {
73 None => None,
74 Some(Object::Array(items)) => Some(ColourKey::parse(items, per_pixel, bits)?),
75 Some(Object::Reference(_)) => {
76 return Err(Error::Unsupported {
77 what: "a /Mask image stencil",
78 });
79 }
80 Some(_) => {
81 return Err(Error::malformed(
82 "a /Mask that is neither an array nor a stream",
83 ));
84 }
85 };
86 if key.is_some() && is_dct(dict) {
87 return Err(Error::Unsupported {
88 what: "colour-key /Mask on a /DCTDecode image",
89 });
90 }
91 if is_dct(dict) {
92 return Self::from_dct(document, stream, id, interpolate);
93 }
94 let decoded = document.decode_stream(stream)?;
95 let data = if bits == 1 {
96 widen_one_bit(&decoded, width, height, per_pixel)?
97 } else {
98 decoded
99 };
100 if data.len() < count {
101 return Err(Error::Malformed {
102 what: "image data is shorter than width × height × components",
103 offset: None,
104 });
105 }
106 let masked = key.map(|key| {
110 data.chunks_exact(per_pixel)
111 .map(|sample| key.masks(sample))
112 .collect::<Vec<bool>>()
113 });
114 let decode = decode_ranges(dict.get(b"Decode"), per_pixel);
115 let mut pixels = Vec::with_capacity((width as usize) * (height as usize));
116 for index in (0..count).step_by(per_pixel) {
117 let sample = &data[index..index + per_pixel];
118 let mut components = [0.0_f64; 4];
119 for (slot, byte) in sample.iter().enumerate().take(per_pixel) {
120 let (from, to) = decode[slot];
121 components[slot] = (from + f64::from(*byte) / 255.0 * (to - from)).clamp(0.0, 1.0);
122 }
123 pixels.push(colour_at(&colours, &components));
124 }
125 Ok(Self {
126 width,
127 height,
128 pixels,
129 interpolate,
130 masked,
131 })
132 }
133
134 #[cfg(feature = "dct")]
142 fn from_dct(
143 document: &Document,
144 _stream: &Stream,
145 id: Option<pdf2::ObjectId>,
146 interpolate: bool,
147 ) -> Result<Self> {
148 let Some(id) = id else {
149 return Err(Error::malformed(
150 "a /DCTDecode image without an object number",
151 ));
152 };
153 let data = document.stream_bytes(id)?;
154 let cmyk = dict_component_count(_stream) == Some(4);
160 let mut decoder =
161 zune_jpeg::JpegDecoder::new(zune_jpeg::zune_core::bytestream::ZCursor::new(&data));
162 if cmyk {
163 decoder.set_options(
164 zune_jpeg::zune_core::options::DecoderOptions::default()
165 .jpeg_set_out_colorspace(zune_jpeg::zune_core::colorspace::ColorSpace::CMYK),
166 );
167 }
168 let pixels = decoder
169 .decode()
170 .map_err(|_| Error::malformed("/DCTDecode payload"))?;
171 let Some(info) = decoder.info() else {
172 return Err(Error::malformed(
173 "/DCTDecode payload without a frame header",
174 ));
175 };
176 let components = match decoder.output_colorspace() {
177 Some(zune_jpeg::zune_core::colorspace::ColorSpace::Luma) => 1,
178 Some(zune_jpeg::zune_core::colorspace::ColorSpace::CMYK) => 4,
179 _ => 3,
180 };
181 let count = usize::from(info.width)
182 .checked_mul(usize::from(info.height))
183 .and_then(|samples| samples.checked_mul(components))
184 .ok_or_else(|| Error::malformed("image dimensions overflow"))?;
185 let limit = document.decoded_limit();
186 if count > limit {
187 return Err(Error::Limit {
188 what: "a /DCTDecode image of the size its header declares",
189 limit,
190 });
191 }
192 if pixels.len() < count {
193 return Err(Error::malformed(
194 "/DCTDecode payload is shorter than its header",
195 ));
196 }
197 let stated_decode = _stream.dict().get(b"Decode").is_some();
203 let invert = cmyk && !stated_decode && has_adobe_marker(&data);
204 let decode = decode_ranges(_stream.dict().get(b"Decode"), components);
207 let sample = |bytes: &[u8]| -> Vec<f64> {
208 bytes
209 .iter()
210 .enumerate()
211 .map(|(index, byte)| {
212 let value = f64::from(*byte) / 255.0;
213 let (from, to) = decode[index.min(decode.len() - 1)];
214 (from + value * (to - from)).clamp(0.0, 1.0)
215 })
216 .collect()
217 };
218 let pixels = pixels[..count]
219 .chunks_exact(components)
220 .map(|bytes| {
221 let bytes: Vec<u8> = if invert {
222 bytes.iter().map(|byte| 255 - byte).collect()
223 } else {
224 bytes.to_vec()
225 };
226 let values = sample(&bytes);
227 match components {
228 1 => Color::rgb(values[0], values[0], values[0]),
229 4 => Color::from_cmyk(values[0], values[1], values[2], values[3]),
230 _ => Color::rgb(values[0], values[1], values[2]),
231 }
232 })
233 .collect();
234 Ok(Self {
235 width: u32::from(info.width),
236 height: u32::from(info.height),
237 pixels,
238 interpolate,
239 masked: None,
242 })
243 }
244
245 #[cfg(not(feature = "dct"))]
247 fn from_dct(
248 _document: &Document,
249 _stream: &Stream,
250 _id: Option<pdf2::ObjectId>,
251 _interpolate: bool,
252 ) -> Result<Self> {
253 Err(Error::Unsupported {
254 what: "/DCTDecode images (build with the `dct` feature)",
255 })
256 }
257
258 fn is_masked(&self, u: f64, v: f64) -> bool {
260 let Some(masked) = &self.masked else {
261 return false;
262 };
263 if self.width == 0 || self.height == 0 {
264 return false;
265 }
266 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
267 let x = (u.clamp(0.0, 1.0) * f64::from(self.width)) as u32;
268 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
269 let y = (v.clamp(0.0, 1.0) * f64::from(self.height)) as u32;
270 let x = x.min(self.width - 1);
271 let y = y.min(self.height - 1);
272 masked
273 .get((y * self.width + x) as usize)
274 .copied()
275 .unwrap_or(false)
276 }
277
278 pub fn width(&self) -> u32 {
280 self.width
281 }
282
283 pub fn height(&self) -> u32 {
285 self.height
286 }
287
288 pub fn sample(&self, u: f64, v: f64) -> Color {
290 if self.width == 0 || self.height == 0 {
291 return Color::WHITE;
292 }
293 let x = (u.clamp(0.0, 1.0) * f64::from(self.width) - 0.5).max(0.0);
294 let y = (v.clamp(0.0, 1.0) * f64::from(self.height) - 0.5).max(0.0);
295 if !self.interpolate {
296 return self.pixel(x.round() as u32, y.round() as u32);
297 }
298 let x0 = x.floor() as u32;
299 let y0 = y.floor() as u32;
300 let x1 = (x0 + 1).min(self.width - 1);
301 let y1 = (y0 + 1).min(self.height - 1);
302 let fx = x - f64::from(x0);
303 let fy = y - f64::from(y0);
304 let top = mix(self.pixel(x0, y0), self.pixel(x1, y0), fx);
305 let bottom = mix(self.pixel(x0, y1), self.pixel(x1, y1), fx);
306 mix(top, bottom, fy)
307 }
308
309 fn pixel(&self, x: u32, y: u32) -> Color {
310 let x = x.min(self.width - 1);
311 let y = y.min(self.height - 1);
312 self.pixels[(y as usize) * (self.width as usize) + (x as usize)]
313 }
314
315 pub fn paint(
317 &self,
318 canvas: &mut Canvas,
319 mask: &ClipMask,
320 ctm: Matrix,
321 alpha: f64,
322 mode: BlendMode,
323 ) {
324 let Some(inverse) = ctm.invert() else {
325 return;
326 };
327 let corners = [
328 ctm.apply(Point::new(0.0, 0.0)),
329 ctm.apply(Point::new(1.0, 0.0)),
330 ctm.apply(Point::new(0.0, 1.0)),
331 ctm.apply(Point::new(1.0, 1.0)),
332 ];
333 let min_x = corners
334 .iter()
335 .fold(f64::INFINITY, |min, point| min.min(point.x))
336 .floor()
337 .max(0.0);
338 let max_x = corners
339 .iter()
340 .fold(f64::NEG_INFINITY, |max, point| max.max(point.x))
341 .ceil()
342 .min(f64::from(canvas.width()));
343 let min_y = corners
344 .iter()
345 .fold(f64::INFINITY, |min, point| min.min(point.y))
346 .floor()
347 .max(0.0);
348 let max_y = corners
349 .iter()
350 .fold(f64::NEG_INFINITY, |max, point| max.max(point.y))
351 .ceil()
352 .min(f64::from(canvas.height()));
353 for y in min_y as u32..max_y as u32 {
354 for x in min_x as u32..max_x as u32 {
355 let coverage = mask.alpha(x, y);
356 if coverage <= 0.0 {
357 continue;
358 }
359 let device = Point::new(f64::from(x) + 0.5, f64::from(y) + 0.5);
360 let user = inverse.apply(device);
361 if !(0.0..=1.0).contains(&user.x) || !(0.0..=1.0).contains(&user.y) {
362 continue;
363 }
364 let v = 1.0 - user.y;
367 if self.is_masked(user.x, v) {
368 continue;
372 }
373 let colour = self.sample(user.x, v);
374 canvas.blend_with(x, y, colour, alpha * coverage, mode);
375 }
376 }
377 }
378}
379
380#[derive(Debug, Clone, PartialEq, Eq)]
386struct ColourKey {
387 min: [u8; 4],
388 max: [u8; 4],
389 components: usize,
390}
391
392impl ColourKey {
393 fn parse(items: &[Object], components: usize, bits: i64) -> Result<Self> {
396 if items.len() != components * 2 {
397 return Err(Error::malformed(
398 "a /Mask whose length is not twice the image's component count",
399 ));
400 }
401 let scale = if bits == 1 { 255.0 } else { 1.0 };
402 let limit = if bits == 1 { 1.0 } else { 255.0 };
403 let mut min = [0_u8; 4];
404 let mut max = [0_u8; 4];
405 for slot in 0..components {
406 let low = items[slot * 2].as_real().unwrap_or(-1.0);
407 let high = items[slot * 2 + 1].as_real().unwrap_or(-1.0);
408 if !(0.0..=limit).contains(&low) || !(0.0..=limit).contains(&high) {
409 return Err(Error::malformed("a /Mask value outside the sample range"));
410 }
411 min[slot] = (low * scale).round() as u8;
412 max[slot] = (high * scale).round() as u8;
413 }
414 Ok(Self {
415 min,
416 max,
417 components,
418 })
419 }
420
421 fn masks(&self, sample: &[u8]) -> bool {
423 sample
424 .iter()
425 .take(self.components)
426 .enumerate()
427 .all(|(slot, byte)| (self.min[slot]..=self.max[slot]).contains(byte))
428 }
429}
430
431fn decode_ranges(decode: Option<&Object>, components: usize) -> Vec<(f64, f64)> {
433 let mut ranges = vec![(0.0, 1.0); components];
434 let Some(Object::Array(items)) = decode else {
435 return ranges;
436 };
437 if items.len() < components * 2 {
438 return ranges;
439 }
440 for (slot, pair) in items.as_chunks::<2>().0.iter().enumerate().take(components) {
441 let (Some(from), Some(to)) = (pair[0].as_real(), pair[1].as_real()) else {
442 continue;
443 };
444 ranges[slot] = (from, to);
445 }
446 ranges
447}
448
449fn colour_at(colours: &ColourSpace, components: &[f64; 4]) -> Color {
451 match colours {
452 ColourSpace::Gray => Color::rgb(components[0], components[0], components[0]),
453 ColourSpace::Rgb => Color::rgb(components[0], components[1], components[2]),
454 ColourSpace::Cmyk => {
455 Color::from_cmyk(components[0], components[1], components[2], components[3])
456 }
457 ColourSpace::Indexed { base, lookup } => {
458 let index = (components[0] * 255.0).round().max(0.0) as usize;
461 let count = base.components();
462 let entry = index * count;
463 let slice = lookup.get(entry..entry + count).unwrap_or(&[]);
464 if slice.len() < count {
465 return Color::BLACK;
466 }
467 let mut table = [0.0_f64; 4];
468 for (slot, byte) in slice.iter().enumerate().take(4) {
469 table[slot] = f64::from(*byte) / 255.0;
470 }
471 colour_at(base, &table)
472 }
473 }
474}
475
476fn mix(left: Color, right: Color, t: f64) -> Color {
477 let t = t.clamp(0.0, 1.0);
478 Color::rgb(
479 left.r * (1.0 - t) + right.r * t,
480 left.g * (1.0 - t) + right.g * t,
481 left.b * (1.0 - t) + right.b * t,
482 )
483}
484
485#[derive(Debug, Clone, PartialEq)]
487enum ColourSpace {
488 Gray,
489 Rgb,
490 Cmyk,
491 Indexed {
492 base: Box<ColourSpace>,
493 lookup: Vec<u8>,
494 },
495}
496
497impl ColourSpace {
498 fn from_object(document: &Document, object: Object) -> Result<Self> {
499 match object {
500 Object::Name(name) => match name.as_slice() {
501 b"DeviceGray" | b"G" | b"CalGray" => Ok(Self::Gray),
502 b"DeviceRGB" | b"RGB" | b"CalRGB" => Ok(Self::Rgb),
503 b"DeviceCMYK" | b"CMYK" => Ok(Self::Cmyk),
504 _ => Err(Error::malformed("unsupported image /ColorSpace")),
505 },
506 Object::Array(items) => {
507 let family = match items.first() {
508 Some(Object::Name(name)) => name.clone(),
509 _ => return Err(Error::malformed("image /ColorSpace array family")),
510 };
511 match family.as_slice() {
512 b"Indexed" | b"I" => {
513 let base = match items.get(1) {
514 Some(base) => {
515 Self::from_object(document, resolve(document, Some(base))?)?
516 }
517 None => return Err(Error::malformed("Indexed image without a base")),
518 };
519 let lookup = match items.get(3) {
520 Some(Object::String(string)) => string.as_bytes().to_vec(),
521 Some(Object::Reference(id)) => document.stream_data(*id)?,
522 _ => {
523 return Err(Error::malformed(
524 "Indexed image without a lookup table",
525 ));
526 }
527 };
528 Ok(Self::Indexed {
529 base: Box::new(base),
530 lookup,
531 })
532 }
533 b"ICCBased" => {
534 let stream = match items.get(1) {
535 Some(Object::Reference(id)) => document.stream(*id)?,
536 _ => return Err(Error::malformed("ICCBased without a stream")),
537 };
538 let components = stream
539 .dict()
540 .get(b"N")
541 .and_then(Object::as_integer)
542 .unwrap_or(3);
543 match components {
544 1 => Ok(Self::Gray),
545 3 => Ok(Self::Rgb),
546 4 => Ok(Self::Cmyk),
547 _ => Err(Error::malformed("unsupported ICCBased components")),
548 }
549 }
550 _ => Err(Error::malformed("unsupported image /ColorSpace array")),
551 }
552 }
553 _ => Err(Error::malformed("unsupported image /ColorSpace value")),
554 }
555 }
556
557 fn components(&self) -> usize {
558 match self {
559 Self::Gray => 1,
560 Self::Rgb => 3,
561 Self::Cmyk => 4,
562 Self::Indexed { .. } => 1,
563 }
564 }
565}
566
567fn integer(dict: &Dictionary, key: &[u8]) -> Result<u32> {
568 dict.get(key)
569 .and_then(Object::as_integer)
570 .and_then(|value| u32::try_from(value).ok())
571 .ok_or_else(|| Error::malformed("image without integer /Width and /Height"))
572}
573
574fn dict_component_count(stream: &Stream) -> Option<usize> {
577 match stream.dict().get(b"ColorSpace") {
578 Some(Object::Name(name)) if name == b"DeviceCMYK" => Some(4),
579 Some(Object::Name(name)) if name == b"DeviceGray" => Some(1),
580 Some(Object::Name(name)) if name == b"DeviceRGB" => Some(3),
581 _ => None,
582 }
583}
584
585fn widen_one_bit(data: &[u8], width: u32, height: u32, components: usize) -> Result<Vec<u8>> {
590 if components != 1 {
591 return Err(Error::malformed(
592 "one-bit samples need a single-component colour space",
593 ));
594 }
595 let bits_per_row = usize::try_from(width).unwrap_or(0);
596 let stride = bits_per_row.div_ceil(8);
597 let rows = usize::try_from(height).unwrap_or(0);
598 if data.len() < stride.saturating_mul(rows) {
599 return Err(Error::malformed(
600 "one-bit image data is shorter than its rows",
601 ));
602 }
603 let mut out = Vec::with_capacity(bits_per_row.saturating_mul(rows));
604 for row in 0..rows {
605 for column in 0..bits_per_row {
606 let byte = data[row * stride + column / 8];
607 let shift = 7 - column % 8;
608 let bit = (byte >> shift) & 1;
609 out.push(if bit == 1 { 255 } else { 0 });
610 }
611 }
612 Ok(out)
613}
614
615fn has_adobe_marker(data: &[u8]) -> bool {
622 let mut index = 2; while index + 4 <= data.len() {
624 if data[index] != 0xFF {
625 return false;
626 }
627 let marker = data[index + 1];
628 if matches!(marker, 0xD8 | 0x01 | 0xD0..=0xD7) {
630 index += 2;
631 continue;
632 }
633 let length = usize::from(u16::from_be_bytes([data[index + 2], data[index + 3]]));
634 if length < 2 {
635 return false;
636 }
637 if marker == 0xEE {
638 let payload = &data[index + 4..(index + 2 + length).min(data.len())];
639 return payload.starts_with(b"Adobe");
640 }
641 if marker == 0xDA {
643 return false;
644 }
645 index += 2 + length;
646 }
647 false
648}
649
650fn is_dct(dict: &Dictionary) -> bool {
652 match dict.get(b"Filter") {
653 Some(Object::Name(name)) => name == b"DCTDecode",
654 Some(Object::Array(items)) => items
655 .iter()
656 .rev()
657 .find_map(Object::as_name)
658 .is_some_and(|name| name == b"DCTDecode"),
659 _ => false,
660 }
661}
662
663pub(crate) fn resolve(document: &Document, object: Option<&Object>) -> Result<Object> {
665 match object {
666 Some(Object::Reference(id)) => document.get_object(*id),
667 Some(other) => Ok(other.clone()),
668 None => Ok(Object::Null),
669 }
670}
671
672#[cfg(test)]
673mod tests {
674 use super::Image;
675 use crate::canvas::{BlendMode, Canvas, ClipMask, Color};
676 use crate::geom::Matrix;
677
678 fn image(width: u32, height: u32, interpolate: bool) -> Image {
679 let mut pixels = Vec::new();
680 for y in 0..height {
681 for x in 0..width {
682 pixels.push(if (x + y) % 2 == 0 {
683 Color::BLACK
684 } else {
685 Color::WHITE
686 });
687 }
688 }
689 Image {
690 width,
691 height,
692 pixels,
693 interpolate,
694 masked: None,
695 }
696 }
697
698 #[test]
699 fn nearest_sampling_returns_whole_pixels() {
700 let image = image(2, 2, false);
701 assert_eq!(image.sample(0.25, 0.25), Color::BLACK);
702 assert_eq!(image.sample(0.75, 0.25), Color::WHITE);
703 assert_eq!(image.sample(0.25, 0.75), Color::WHITE);
704 }
705
706 #[test]
707 fn bilinear_sampling_blends_neighbours() {
708 let image = image(2, 2, true);
709 let middle = image.sample(0.5, 0.5);
710 assert!((middle.r - 0.5).abs() < 1e-9, "{middle:?}");
711 }
712
713 #[test]
714 fn painting_covers_the_unit_square_transform() {
715 let image = image(2, 2, false);
716 let mut canvas = Canvas::new(4, 4, Color::WHITE);
717 let mask = ClipMask::all(4, 4);
718 let ctm = Matrix::new(4.0, 0.0, 0.0, -4.0, 0.0, 4.0);
720 image.paint(&mut canvas, &mask, ctm, 1.0, BlendMode::Normal);
721 assert_eq!(canvas.pixel(0, 0), Some([0, 0, 0, 255]));
722 assert_eq!(canvas.pixel(3, 0), Some([255, 255, 255, 255]));
723 assert_eq!(canvas.pixel(0, 3), Some([255, 255, 255, 255]));
724 assert_eq!(canvas.pixel(3, 3), Some([0, 0, 0, 255]));
725 }
726}