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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
use byteorder::{LittleEndian, ReadBytesExt};
use std::io::{Cursor, Read, Seek, SeekFrom};
use color::ColorType;
use image::{ImageDecoder, ImageError, ImageResult};
use self::InnerDecoder::*;
use bmp::BMPDecoder;
use png::PNGDecoder;
const PNG_SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10];
pub struct ICODecoder<R: Read> {
selected_entry: DirEntry,
inner_decoder: InnerDecoder<R>,
}
enum InnerDecoder<R: Read> {
BMP(BMPDecoder<R>),
PNG(PNGDecoder<R>),
}
#[derive(Clone, Copy, Default)]
struct DirEntry {
width: u8,
height: u8,
color_count: u8,
reserved: u8,
num_color_planes: u16,
bits_per_pixel: u16,
image_length: u32,
image_offset: u32,
}
impl<R: Read + Seek> ICODecoder<R> {
pub fn new(mut r: R) -> ImageResult<ICODecoder<R>> {
let entries = try!(read_entries(&mut r));
let entry = try!(best_entry(entries));
let decoder = try!(entry.decoder(r));
Ok(ICODecoder {
selected_entry: entry,
inner_decoder: decoder,
})
}
}
fn read_entries<R: Read>(r: &mut R) -> ImageResult<Vec<DirEntry>> {
let _reserved = try!(r.read_u16::<LittleEndian>());
let _type = try!(r.read_u16::<LittleEndian>());
let count = try!(r.read_u16::<LittleEndian>());
(0..count).map(|_| read_entry(r)).collect()
}
fn read_entry<R: Read>(r: &mut R) -> ImageResult<DirEntry> {
let mut entry = DirEntry::default();
entry.width = try!(r.read_u8());
entry.height = try!(r.read_u8());
entry.color_count = try!(r.read_u8());
entry.reserved = try!(r.read_u8());
entry.num_color_planes = try!(r.read_u16::<LittleEndian>());
if entry.num_color_planes > 256 {
return Err(ImageError::FormatError(
"ICO image entry has a too large color planes/hotspot value".to_string(),
));
}
entry.bits_per_pixel = try!(r.read_u16::<LittleEndian>());
if entry.bits_per_pixel > 256 {
return Err(ImageError::FormatError(
"ICO image entry has a too large bits per pixel/hotspot value".to_string(),
));
}
entry.image_length = try!(r.read_u32::<LittleEndian>());
entry.image_offset = try!(r.read_u32::<LittleEndian>());
Ok(entry)
}
fn best_entry(mut entries: Vec<DirEntry>) -> ImageResult<DirEntry> {
let mut best = try!(entries.pop().ok_or(ImageError::ImageEnd));
let mut best_score = (
best.bits_per_pixel,
u32::from(best.real_width()) * u32::from(best.real_height()),
);
for entry in entries {
let score = (
entry.bits_per_pixel,
u32::from(entry.real_width()) * u32::from(entry.real_height()),
);
if score > best_score {
best = entry;
best_score = score;
}
}
Ok(best)
}
impl DirEntry {
fn real_width(&self) -> u16 {
match self.width {
0 => 256,
w => u16::from(w),
}
}
fn real_height(&self) -> u16 {
match self.height {
0 => 256,
h => u16::from(h),
}
}
fn matches_dimensions(&self, width: u64, height: u64) -> bool {
u64::from(self.real_width()) == width && u64::from(self.real_height()) == height
}
fn seek_to_start<R: Read + Seek>(&self, r: &mut R) -> ImageResult<()> {
try!(r.seek(SeekFrom::Start(u64::from(self.image_offset))));
Ok(())
}
fn is_png<R: Read + Seek>(&self, r: &mut R) -> ImageResult<bool> {
try!(self.seek_to_start(r));
let mut signature = [0u8; 8];
try!(r.read_exact(&mut signature));
Ok(signature == PNG_SIGNATURE)
}
fn decoder<R: Read + Seek>(&self, mut r: R) -> ImageResult<InnerDecoder<R>> {
let is_png = try!(self.is_png(&mut r));
try!(self.seek_to_start(&mut r));
if is_png {
Ok(PNG(PNGDecoder::new(r)?))
} else {
Ok(BMP(BMPDecoder::new_with_ico_format(r)?))
}
}
}
impl<R: Read + Seek> ImageDecoder for ICODecoder<R> {
type Reader = Cursor<Vec<u8>>;
fn dimensions(&self) -> (u64, u64) {
match self.inner_decoder {
BMP(ref decoder) => decoder.dimensions(),
PNG(ref decoder) => decoder.dimensions(),
}
}
fn colortype(&self) -> ColorType {
match self.inner_decoder {
BMP(ref decoder) => decoder.colortype(),
PNG(ref decoder) => decoder.colortype(),
}
}
fn into_reader(self) -> ImageResult<Self::Reader> {
Ok(Cursor::new(self.read_image()?))
}
fn read_image(self) -> ImageResult<Vec<u8>> {
match self.inner_decoder {
PNG(decoder) => {
if self.selected_entry.image_length < PNG_SIGNATURE.len() as u32 {
return Err(ImageError::FormatError(
"Entry specified a length that is shorter than PNG header!".to_string(),
));
}
let (width, height) = decoder.dimensions();
if !self.selected_entry.matches_dimensions(width, height) {
return Err(ImageError::FormatError(
"Entry and PNG dimensions do not match!".to_string(),
));
}
let color_type = decoder.colortype();
if let ColorType::RGBA(8) = color_type {
} else {
return Err(ImageError::FormatError(
"The PNG is not in RGBA format!".to_string(),
));
}
decoder.read_image()
}
BMP(mut decoder) => {
let (width, height) = decoder.dimensions();
if !self.selected_entry.matches_dimensions(width, height) {
return Err(ImageError::FormatError(
"Entry({:?}) and BMP({:?}) dimensions do not match!".to_string(),
));
}
if decoder.colortype() != ColorType::RGBA(8) {
return Err(ImageError::UnsupportedError(
"Unsupported color type".to_string(),
));
}
let mut pixel_data = decoder.read_image_data()?;
let r = decoder.reader();
let mask_start = try!(r.seek(SeekFrom::Current(0)));
let mask_end =
u64::from(self.selected_entry.image_offset + self.selected_entry.image_length);
let mask_length = mask_end - mask_start;
if mask_length > 0 {
let mask_row_bytes = ((width + 31) / 32) * 4;
let expected_length = u64::from(mask_row_bytes * height);
if mask_length < expected_length {
return Err(ImageError::ImageEnd);
}
for y in 0..height {
let mut x = 0;
for _ in 0..mask_row_bytes {
let mask_byte = try!(r.read_u8());
for bit in (0..8).rev() {
if x >= width {
break;
}
if mask_byte & (1 << bit) != 0 {
pixel_data[((height - y - 1) * width + x) as usize * 4 + 3] = 0;
}
x += 1;
}
}
}
}
Ok(pixel_data)
}
}
}
}