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