1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
//! Reads images in the form that goes into a PDF
//!
//! JPEG data can be used as it is with DCTDecode, and PNG data with FlateDecode. Neither needs
//! to be decompressed first, so no code for compression or decompression has to be written.
//!
//! PNG images with 8 or 16 bits, in gray, RGB, or a palette, are read. Images with
//! transparency (color types 4 and 6) are not read, because separating the transparency
//! would need the data to be decompressed.
use crate::error::Error;
use std::path::Path;
/// How the colors are arranged
#[derive(Debug, Clone, PartialEq)]
pub enum Color {
Gray,
Rgb,
/// A palette. The contents are a sequence of RGB values
Indexed(Vec<u8>),
}
/// One image to put into the PDF
#[derive(Debug, Clone, PartialEq)]
pub struct Picture {
pub width: usize,
pub height: usize,
/// The number of bits per component
pub bits: usize,
pub color: Color,
/// The name to write in the Filter of the PDF
pub filter: &'static str,
/// What to write in the DecodeParms of the PDF. Empty if it is not needed
pub parms: String,
/// The data, which is passed on as it is
pub data: Vec<u8>,
/// The size when nothing is specified (points)
pub natural_width: f64,
pub natural_height: f64,
}
/// Reads an image file
pub fn load(path: &Path) -> Result<Picture, Error> {
let data = std::fs::read(path).map_err(|reason| {
Error::new(format!("cannot read the image {}: {reason}", path.display()), 0)
})?;
if data.starts_with(&[0xff, 0xd8]) {
return jpeg(data);
}
if data.starts_with(&[0x89, b'P', b'N', b'G']) {
return png(data);
}
Err(Error::new(
format!("only PNG and JPEG can be read: {}", path.display()),
0,
))
}
/// The actual width and height when the image is placed at a given size
pub fn fit(picture: &Picture, width: Option<f64>, height: Option<f64>, scale: Option<f64>) -> (f64, f64) {
let ratio = picture.natural_height / picture.natural_width.max(0.001);
match (width, height, scale) {
(Some(width), Some(height), _) => (width, height),
(Some(width), None, _) => (width, width * ratio),
(None, Some(height), _) => (height / ratio.max(0.001), height),
(None, None, Some(scale)) => (
picture.natural_width * scale,
picture.natural_height * scale,
),
(None, None, None) => (picture.natural_width, picture.natural_height),
}
}
/// Reads a JPEG
fn jpeg(data: Vec<u8>) -> Result<Picture, Error> {
let mut at = 2;
let mut density = (72.0, 72.0);
while at + 4 <= data.len() {
if data[at] != 0xff {
at += 1;
continue;
}
let marker = data[at + 1];
let length = u16::from_be_bytes([data[at + 2], data[at + 3]]) as usize;
if marker == 0xe0 && at + 16 <= data.len() && &data[at + 4..at + 8] == b"JFIF" {
let unit = data[at + 11];
let x = u16::from_be_bytes([data[at + 12], data[at + 13]]) as f64;
let y = u16::from_be_bytes([data[at + 14], data[at + 15]]) as f64;
if unit == 1 && x > 0.0 && y > 0.0 {
density = (x, y);
} else if unit == 2 && x > 0.0 && y > 0.0 {
density = (x * 2.54, y * 2.54);
}
}
let start_of_frame = matches!(marker, 0xc0..=0xc3 | 0xc5..=0xc7 | 0xc9..=0xcb | 0xcd..=0xcf);
if start_of_frame {
if at + 10 > data.len() {
break;
}
let bits = data[at + 4] as usize;
let height = u16::from_be_bytes([data[at + 5], data[at + 6]]) as usize;
let width = u16::from_be_bytes([data[at + 7], data[at + 8]]) as usize;
let color = match data[at + 9] {
1 => Color::Gray,
3 => Color::Rgb,
other => {
return Err(Error::new(format!("a JPEG with {other} components cannot be read"), 0));
}
};
return Ok(Picture {
width,
height,
bits,
color,
filter: "DCTDecode",
parms: String::new(),
natural_width: width as f64 * 72.0 / density.0,
natural_height: height as f64 * 72.0 / density.1,
data,
});
}
at += 2 + length;
}
Err(Error::new("the JPEG does not give its size", 0))
}
/// Reads a PNG
fn png(data: Vec<u8>) -> Result<Picture, Error> {
let mut at = 8;
let mut head: Option<(usize, usize, usize, u8)> = None;
let mut palette = Vec::new();
let mut body = Vec::new();
let mut density = (72.0, 72.0);
while at + 8 <= data.len() {
let length = u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]) as usize;
let tag = &data[at + 4..at + 8];
let start = at + 8;
let end = start + length;
if end > data.len() {
break;
}
match tag {
b"IHDR" => {
let width = u32::from_be_bytes([
data[start],
data[start + 1],
data[start + 2],
data[start + 3],
]) as usize;
let height = u32::from_be_bytes([
data[start + 4],
data[start + 5],
data[start + 6],
data[start + 7],
]) as usize;
let bits = data[start + 8] as usize;
let kind = data[start + 9];
if data[start + 12] != 0 {
return Err(Error::new("an interlaced PNG cannot be read", 0));
}
head = Some((width, height, bits, kind));
}
b"PLTE" => palette = data[start..end].to_vec(),
b"IDAT" => body.extend_from_slice(&data[start..end]),
b"pHYs" => {
let x = u32::from_be_bytes([
data[start],
data[start + 1],
data[start + 2],
data[start + 3],
]) as f64;
let y = u32::from_be_bytes([
data[start + 4],
data[start + 5],
data[start + 6],
data[start + 7],
]) as f64;
if data[start + 8] == 1 && x > 0.0 && y > 0.0 {
density = (x * 0.0254, y * 0.0254);
}
}
b"IEND" => break,
_ => {}
}
at = end + 4;
}
let (width, height, bits, kind) = match head {
Some(found) => found,
None => return Err(Error::new("the PNG has no IHDR", 0)),
};
let color = match kind {
0 => Color::Gray,
2 => Color::Rgb,
3 => Color::Indexed(palette),
4 | 6 => {
return Err(Error::new(
"a PNG with transparency cannot be read; remove the transparency",
0,
));
}
other => return Err(Error::new(format!("a PNG of color type {other} cannot be read"), 0)),
};
let colors = match color {
Color::Rgb => 3,
_ => 1,
};
let parms = format!(
"<< /Predictor 15 /Colors {colors} /BitsPerComponent {bits} /Columns {width} >>"
);
Ok(Picture {
width,
height,
bits,
color,
filter: "FlateDecode",
parms,
data: body,
natural_width: width as f64 * 72.0 / density.0,
natural_height: height as f64 * 72.0 / density.1,
})
}