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
extern crate png;
use std::io::{self, Read, Write};
use color::ColorType;
use image::{ImageDecoder, ImageError, ImageResult};
pub struct PNGReader<R: Read> {
reader: png::Reader<R>,
buffer: Vec<u8>,
index: usize,
}
impl<R: Read> PNGReader<R> {
fn new(mut reader: png::Reader<R>) -> ImageResult<PNGReader<R>> {
let len = reader.output_buffer_size();
let buffer = if reader.info().interlaced {
let mut buffer = vec![0; len];
reader.next_frame(&mut buffer)?;
buffer
} else {
Vec::new()
};
Ok(PNGReader {
reader,
buffer,
index: 0,
})
}
}
impl<R: Read> Read for PNGReader<R> {
fn read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> {
let readed = buf.write(&self.buffer[self.index..]).unwrap();
let mut bytes = readed;
self.index += readed;
while self.index >= self.buffer.len() {
match self.reader.next_row()? {
Some(row) => {
let readed = buf.write(row).unwrap();
bytes += readed;
self.buffer = (&row[readed..]).to_owned();
self.index = 0;
}
None => return Ok(bytes)
}
}
Ok(bytes)
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
let mut bytes = self.buffer.len();
buf.extend_from_slice(&self.buffer);
self.buffer = Vec::new();
self.index = 0;
while let Some(row) = self.reader.next_row()? {
buf.extend_from_slice(row);
bytes += row.len();
}
Ok(bytes)
}
}
pub struct PNGDecoder<R: Read> {
colortype: ColorType,
reader: png::Reader<R>,
}
impl<R: Read> PNGDecoder<R> {
pub fn new(r: R) -> ImageResult<PNGDecoder<R>> {
let limits = png::Limits {
bytes: usize::max_value(),
};
let decoder = png::Decoder::new_with_limits(r, limits);
let (_, mut reader) = decoder.read_info()?;
let colortype = reader.output_color_type().into();
Ok(PNGDecoder { colortype, reader })
}
}
impl<'a, R: 'a + Read> ImageDecoder<'a> for PNGDecoder<R> {
type Reader = PNGReader<R>;
fn dimensions(&self) -> (u64, u64) {
let (w, h) = self.reader.info().size();
(u64::from(w), u64::from(h))
}
fn colortype(&self) -> ColorType {
self.colortype
}
fn into_reader(self) -> ImageResult<Self::Reader> {
PNGReader::new(self.reader)
}
fn read_image(mut self) -> ImageResult<Vec<u8>> {
let mut data = vec![0; self.reader.output_buffer_size()];
self.reader.next_frame(&mut data)?;
Ok(data)
}
fn scanline_bytes(&self) -> u64 {
let width = self.reader.info().width;
self.reader.output_line_size(width) as u64
}
}
pub struct PNGEncoder<W: Write> {
w: W,
}
impl<W: Write> PNGEncoder<W> {
pub fn new(w: W) -> PNGEncoder<W> {
PNGEncoder { w }
}
pub fn encode(self, data: &[u8], width: u32, height: u32, color: ColorType) -> io::Result<()> {
let (ct, bits) = color.into();
let mut encoder = png::Encoder::new(self.w, width, height);
encoder.set_color(ct);
encoder.set_depth(bits);
let mut writer = encoder.write_header()?;
writer.write_image_data(data).map_err(|e| e.into())
}
}
impl From<(png::ColorType, png::BitDepth)> for ColorType {
fn from((ct, bits): (png::ColorType, png::BitDepth)) -> ColorType {
use self::png::ColorType::*;
let bits = bits as u8;
match ct {
Grayscale => ColorType::Gray(bits),
RGB => ColorType::RGB(bits),
Indexed => ColorType::Palette(bits),
GrayscaleAlpha => ColorType::GrayA(bits),
RGBA => ColorType::RGBA(bits),
}
}
}
impl From<ColorType> for (png::ColorType, png::BitDepth) {
fn from(ct: ColorType) -> (png::ColorType, png::BitDepth) {
use self::png::ColorType::*;
let (ct, bits) = match ct {
ColorType::Gray(bits) => (Grayscale, bits),
ColorType::RGB(bits) => (RGB, bits),
ColorType::Palette(bits) => (Indexed, bits),
ColorType::GrayA(bits) => (GrayscaleAlpha, bits),
ColorType::RGBA(bits) => (RGBA, bits),
ColorType::BGRA(bits) => (RGBA, bits),
ColorType::BGR(bits) => (RGB, bits),
};
(ct, png::BitDepth::from_u8(bits).unwrap())
}
}
impl From<png::DecodingError> for ImageError {
fn from(err: png::DecodingError) -> ImageError {
use self::png::DecodingError::*;
match err {
IoError(err) => ImageError::IoError(err),
Format(desc) => ImageError::FormatError(desc.into_owned()),
InvalidSignature => ImageError::FormatError("invalid signature".into()),
CrcMismatch { .. } => ImageError::FormatError("CRC error".into()),
Other(desc) => ImageError::FormatError(desc.into_owned()),
CorruptFlateStream => {
ImageError::FormatError("compressed data stream corrupted".into())
}
LimitsExceeded => ImageError::InsufficientMemory,
}
}
}
#[cfg(test)]
mod tests {
use image::ImageDecoder;
use std::io::Read;
use super::*;
#[test]
fn ensure_no_decoder_off_by_one() {
let dec = PNGDecoder::new(std::fs::File::open("tests/images/png/bugfixes/debug_triangle_corners_widescreen.png").unwrap())
.expect("Unable to read PNG file (does it exist?)");
assert_eq![(2000, 1000), dec.dimensions()];
assert_eq![
ColorType::RGB(8),
dec.colortype(),
"Image MUST have the RGB(8) format"
];
let correct_bytes = dec
.into_reader()
.expect("Unable to read file")
.bytes()
.map(|x| x.expect("Unable to read byte"))
.collect::<Vec<u8>>();
assert_eq![6_000_000, correct_bytes.len()];
}
}