1use pdf2::{Dictionary, Document, Object, Stream};
4
5use crate::canvas::{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}
17
18impl Image {
19 pub fn from_stream(document: &Document, stream: &Stream) -> Result<Self> {
25 let dict = stream.dict();
26 let width = integer(dict, b"Width")?;
27 let height = integer(dict, b"Height")?;
28 if width == 0 || height == 0 {
29 return Err(Error::malformed("image with zero width or height"));
30 }
31 let bits = dict
32 .get(b"BitsPerComponent")
33 .and_then(Object::as_integer)
34 .unwrap_or(8);
35 if bits != 8 {
36 return Err(Error::malformed(
37 "only 8 bits per component images are rendered",
38 ));
39 }
40 let interpolate = matches!(dict.get(b"Interpolate"), Some(Object::Boolean(true)));
41 let space = resolve(document, dict.get(b"ColorSpace"))?;
42 let data = document.decode_stream(stream)?;
43 let colours = ColourSpace::from_object(document, space)?;
44 let per_pixel = colours.components();
45 let count = (width as usize)
46 .checked_mul(height as usize)
47 .and_then(|pixels| pixels.checked_mul(per_pixel))
48 .ok_or_else(|| Error::malformed("image dimensions overflow"))?;
49 if data.len() < count {
50 return Err(Error::Malformed {
51 what: "image data is shorter than width × height × components",
52 offset: None,
53 });
54 }
55 let decode = decode_ranges(dict.get(b"Decode"), per_pixel);
59 let mut pixels = Vec::with_capacity((width as usize) * (height as usize));
60 for index in (0..count).step_by(per_pixel) {
61 let sample = &data[index..index + per_pixel];
62 let mut components = [0.0_f64; 4];
63 for (slot, byte) in sample.iter().enumerate().take(per_pixel) {
64 let (from, to) = decode[slot];
65 components[slot] = (from + f64::from(*byte) / 255.0 * (to - from)).clamp(0.0, 1.0);
66 }
67 pixels.push(colour_at(&colours, &components));
68 }
69 Ok(Self {
70 width,
71 height,
72 pixels,
73 interpolate,
74 })
75 }
76
77 pub fn width(&self) -> u32 {
79 self.width
80 }
81
82 pub fn height(&self) -> u32 {
84 self.height
85 }
86
87 pub fn sample(&self, u: f64, v: f64) -> Color {
89 if self.width == 0 || self.height == 0 {
90 return Color::WHITE;
91 }
92 let x = (u.clamp(0.0, 1.0) * f64::from(self.width) - 0.5).max(0.0);
93 let y = (v.clamp(0.0, 1.0) * f64::from(self.height) - 0.5).max(0.0);
94 if !self.interpolate {
95 return self.pixel(x.round() as u32, y.round() as u32);
96 }
97 let x0 = x.floor() as u32;
98 let y0 = y.floor() as u32;
99 let x1 = (x0 + 1).min(self.width - 1);
100 let y1 = (y0 + 1).min(self.height - 1);
101 let fx = x - f64::from(x0);
102 let fy = y - f64::from(y0);
103 let top = mix(self.pixel(x0, y0), self.pixel(x1, y0), fx);
104 let bottom = mix(self.pixel(x0, y1), self.pixel(x1, y1), fx);
105 mix(top, bottom, fy)
106 }
107
108 fn pixel(&self, x: u32, y: u32) -> Color {
109 let x = x.min(self.width - 1);
110 let y = y.min(self.height - 1);
111 self.pixels[(y as usize) * (self.width as usize) + (x as usize)]
112 }
113
114 pub fn paint(&self, canvas: &mut Canvas, mask: &ClipMask, ctm: Matrix) {
116 let Some(inverse) = ctm.invert() else {
117 return;
118 };
119 let corners = [
120 ctm.apply(Point::new(0.0, 0.0)),
121 ctm.apply(Point::new(1.0, 0.0)),
122 ctm.apply(Point::new(0.0, 1.0)),
123 ctm.apply(Point::new(1.0, 1.0)),
124 ];
125 let min_x = corners
126 .iter()
127 .fold(f64::INFINITY, |min, point| min.min(point.x))
128 .floor()
129 .max(0.0);
130 let max_x = corners
131 .iter()
132 .fold(f64::NEG_INFINITY, |max, point| max.max(point.x))
133 .ceil()
134 .min(f64::from(canvas.width()));
135 let min_y = corners
136 .iter()
137 .fold(f64::INFINITY, |min, point| min.min(point.y))
138 .floor()
139 .max(0.0);
140 let max_y = corners
141 .iter()
142 .fold(f64::NEG_INFINITY, |max, point| max.max(point.y))
143 .ceil()
144 .min(f64::from(canvas.height()));
145 for y in min_y as u32..max_y as u32 {
146 for x in min_x as u32..max_x as u32 {
147 if !mask.contains(x, y) {
148 continue;
149 }
150 let device = Point::new(f64::from(x) + 0.5, f64::from(y) + 0.5);
151 let user = inverse.apply(device);
152 if !(0.0..=1.0).contains(&user.x) || !(0.0..=1.0).contains(&user.y) {
153 continue;
154 }
155 let colour = self.sample(user.x, 1.0 - user.y);
158 canvas.blend(x, y, colour, 1.0);
159 }
160 }
161 }
162}
163
164fn decode_ranges(decode: Option<&Object>, components: usize) -> Vec<(f64, f64)> {
166 let mut ranges = vec![(0.0, 1.0); components];
167 let Some(Object::Array(items)) = decode else {
168 return ranges;
169 };
170 if items.len() < components * 2 {
171 return ranges;
172 }
173 for (slot, pair) in items.chunks_exact(2).enumerate().take(components) {
174 let (Some(from), Some(to)) = (pair[0].as_real(), pair[1].as_real()) else {
175 continue;
176 };
177 ranges[slot] = (from, to);
178 }
179 ranges
180}
181
182fn colour_at(colours: &ColourSpace, components: &[f64; 4]) -> Color {
184 match colours {
185 ColourSpace::Gray => Color::rgb(components[0], components[0], components[0]),
186 ColourSpace::Rgb => Color::rgb(components[0], components[1], components[2]),
187 ColourSpace::Cmyk => {
188 Color::from_cmyk(components[0], components[1], components[2], components[3])
189 }
190 ColourSpace::Indexed { base, lookup } => {
191 let index = (components[0] * 255.0).round().max(0.0) as usize;
194 let count = base.components();
195 let entry = index * count;
196 let slice = lookup.get(entry..entry + count).unwrap_or(&[]);
197 if slice.len() < count {
198 return Color::BLACK;
199 }
200 let mut table = [0.0_f64; 4];
201 for (slot, byte) in slice.iter().enumerate().take(4) {
202 table[slot] = f64::from(*byte) / 255.0;
203 }
204 colour_at(base, &table)
205 }
206 }
207}
208
209fn mix(left: Color, right: Color, t: f64) -> Color {
210 let t = t.clamp(0.0, 1.0);
211 Color::rgb(
212 left.r * (1.0 - t) + right.r * t,
213 left.g * (1.0 - t) + right.g * t,
214 left.b * (1.0 - t) + right.b * t,
215 )
216}
217
218#[derive(Debug, Clone, PartialEq)]
220enum ColourSpace {
221 Gray,
222 Rgb,
223 Cmyk,
224 Indexed {
225 base: Box<ColourSpace>,
226 lookup: Vec<u8>,
227 },
228}
229
230impl ColourSpace {
231 fn from_object(document: &Document, object: Object) -> Result<Self> {
232 match object {
233 Object::Name(name) => match name.as_slice() {
234 b"DeviceGray" | b"G" | b"CalGray" => Ok(Self::Gray),
235 b"DeviceRGB" | b"RGB" | b"CalRGB" => Ok(Self::Rgb),
236 b"DeviceCMYK" | b"CMYK" => Ok(Self::Cmyk),
237 _ => Err(Error::malformed("unsupported image /ColorSpace")),
238 },
239 Object::Array(items) => {
240 let family = match items.first() {
241 Some(Object::Name(name)) => name.clone(),
242 _ => return Err(Error::malformed("image /ColorSpace array family")),
243 };
244 match family.as_slice() {
245 b"Indexed" | b"I" => {
246 let base = match items.get(1) {
247 Some(base) => {
248 Self::from_object(document, resolve(document, Some(base))?)?
249 }
250 None => return Err(Error::malformed("Indexed image without a base")),
251 };
252 let lookup = match items.get(3) {
253 Some(Object::String(string)) => string.as_bytes().to_vec(),
254 Some(Object::Reference(id)) => document.stream_data(*id)?,
255 _ => {
256 return Err(Error::malformed(
257 "Indexed image without a lookup table",
258 ))
259 }
260 };
261 Ok(Self::Indexed {
262 base: Box::new(base),
263 lookup,
264 })
265 }
266 b"ICCBased" => {
267 let stream = match items.get(1) {
268 Some(Object::Reference(id)) => document.stream(*id)?,
269 _ => return Err(Error::malformed("ICCBased without a stream")),
270 };
271 let components = stream
272 .dict()
273 .get(b"N")
274 .and_then(Object::as_integer)
275 .unwrap_or(3);
276 match components {
277 1 => Ok(Self::Gray),
278 3 => Ok(Self::Rgb),
279 4 => Ok(Self::Cmyk),
280 _ => Err(Error::malformed("unsupported ICCBased components")),
281 }
282 }
283 _ => Err(Error::malformed("unsupported image /ColorSpace array")),
284 }
285 }
286 _ => Err(Error::malformed("unsupported image /ColorSpace value")),
287 }
288 }
289
290 fn components(&self) -> usize {
291 match self {
292 Self::Gray => 1,
293 Self::Rgb => 3,
294 Self::Cmyk => 4,
295 Self::Indexed { .. } => 1,
296 }
297 }
298}
299
300fn integer(dict: &Dictionary, key: &[u8]) -> Result<u32> {
301 dict.get(key)
302 .and_then(Object::as_integer)
303 .and_then(|value| u32::try_from(value).ok())
304 .ok_or_else(|| Error::malformed("image without integer /Width and /Height"))
305}
306
307pub(crate) fn resolve(document: &Document, object: Option<&Object>) -> Result<Object> {
309 match object {
310 Some(Object::Reference(id)) => document.get_object(*id),
311 Some(other) => Ok(other.clone()),
312 None => Ok(Object::Null),
313 }
314}
315
316#[cfg(test)]
317mod tests {
318 use super::Image;
319 use crate::canvas::{Canvas, ClipMask, Color};
320 use crate::geom::Matrix;
321
322 fn image(width: u32, height: u32, interpolate: bool) -> Image {
323 let mut pixels = Vec::new();
324 for y in 0..height {
325 for x in 0..width {
326 pixels.push(if (x + y) % 2 == 0 {
327 Color::BLACK
328 } else {
329 Color::WHITE
330 });
331 }
332 }
333 Image {
334 width,
335 height,
336 pixels,
337 interpolate,
338 }
339 }
340
341 #[test]
342 fn nearest_sampling_returns_whole_pixels() {
343 let image = image(2, 2, false);
344 assert_eq!(image.sample(0.25, 0.25), Color::BLACK);
345 assert_eq!(image.sample(0.75, 0.25), Color::WHITE);
346 assert_eq!(image.sample(0.25, 0.75), Color::WHITE);
347 }
348
349 #[test]
350 fn bilinear_sampling_blends_neighbours() {
351 let image = image(2, 2, true);
352 let middle = image.sample(0.5, 0.5);
353 assert!((middle.r - 0.5).abs() < 1e-9, "{middle:?}");
354 }
355
356 #[test]
357 fn painting_covers_the_unit_square_transform() {
358 let image = image(2, 2, false);
359 let mut canvas = Canvas::new(4, 4, Color::WHITE);
360 let mask = ClipMask::all(4, 4);
361 let ctm = Matrix::new(4.0, 0.0, 0.0, -4.0, 0.0, 4.0);
363 image.paint(&mut canvas, &mask, ctm);
364 assert_eq!(canvas.pixel(0, 0), Some([0, 0, 0, 255]));
365 assert_eq!(canvas.pixel(3, 0), Some([255, 255, 255, 255]));
366 assert_eq!(canvas.pixel(0, 3), Some([255, 255, 255, 255]));
367 assert_eq!(canvas.pixel(3, 3), Some([0, 0, 0, 255]));
368 }
369}