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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
use buffer::{ImageBuffer, Pixel, ArrayLike};
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::old_io;
use std::old_io::IoResult;
use std::num::Int;
use color::{Rgb, Rgba};
use utils::lzw;
use utils::bitstream::LsbWriter;
use imageops::ColorMap;
use super::{Extension, Block, DisposalMethod};
use math::nq;
#[derive(Debug, Copy)]
#[allow(unused_qualifications)]
pub enum ColorMode {
TrueColor,
Indexed(u8),
}
use self::ColorMode::{TrueColor, Indexed};
pub struct Encoder<Image> {
image: Image,
bg_color: Option<Rgb<u8>>,
color_mode: ColorMode
}
const TRANSPARENT: Rgba<u8> = Rgba([0, 0, 0, 0]);
impl<Container> Encoder<ImageBuffer<Rgba<u8>, Container>>
where Container: ArrayLike<u8> {
pub fn new(image: ImageBuffer<Rgba<u8>, Container>,
bg_color: Option<Rgb<u8>>,
color_mode: ColorMode,
) -> Encoder<ImageBuffer<Rgba<u8>, Container>> {
Encoder {
image: image,
bg_color: bg_color,
color_mode: color_mode
}
}
pub fn encode<W: Writer>(&mut self, w: &mut W) -> IoResult<()> {
try!(w.write_all(b"GIF89a"));
let height = self.image.height();
let width = self.image.width();
if width > <u16 as Int>::max_value() as u32 ||
height > <u16 as Int>::max_value() as u32 {
return Err(old_io::IoError{
kind: old_io::InvalidInput,
desc: "Image dimensions are to large for the gif format.",
detail: None
})
}
try!(w.write_le_u16(width as u16));
try!(w.write_le_u16(height as u16));
let (hist, transparent) = self.histogram();
let num_colors = hist.len();
try!(self.write_global_table(w, &hist));
match self.color_mode {
TrueColor if num_colors <= 256 => {
try!(self.write_control_ext(w, 0, transparent));
try!(self.write_descriptor(w, None));
try!(self.write_image_simple(w, &hist, transparent));
},
TrueColor => {
try!(self.write_true_color(w, hist, transparent));
},
Indexed(n) if n as usize <= num_colors && num_colors <= 256 => {
try!(self.write_control_ext(w, 0, transparent));
try!(self.write_descriptor(w, None));
try!(self.write_image_simple(w, &hist, transparent));
}
Indexed(n) => {
try!(self.write_indexed_colors(w, n))
}
}
w.write_u8(Block::Trailer as u8)
}
fn histogram(&self) -> (Vec<(Rgba<u8>, usize)>, Option<usize>){
let mut hist: HashMap<_, usize> = HashMap::new();
if let Some(bg_color) = self.bg_color {
let _ = hist.insert(bg_color.to_rgba(), 0);
}
for p in self.image.pixels() {
let mut p = *p;
if let Some(bg_color) = self.bg_color {
p.blend(&bg_color.to_rgba())
} else if p[3] < 250 {
p = TRANSPARENT;
}
match hist.entry(p) {
Occupied(mut entry) => {
let val = entry.get_mut();
*val = *val + 1;
},
Vacant(entry) => {
entry.insert(1);
}
}
}
let mut colors: Vec<(Rgba<u8>, usize)> = hist.into_iter().collect();
colors.sort_by(|a, b| b.1.cmp(&a.1));
let transparent = colors.iter().position(|x| x.0 == TRANSPARENT);
(colors, transparent)
}
fn write_global_table<W: Writer>(&mut self,
w: &mut W,
hist: &[(Rgba<u8>, usize)]
) -> IoResult<()>
{
let num_colors = hist.len();
let mut flags = 0;
flags |= 1 << 4;
let n = flag_n(num_colors);
flags |= n << 4;
let (global_table, bg_index) = if num_colors <= 256 {
flags |= 1 << 7;
flags |= n;
let mut bg_index = 0;
let mut table = Vec::with_capacity(3*(2 << n));
for (i, &(color, _)) in hist.iter().enumerate() {
let channels = &color.channels()[..3];
if let Some(bg_color) = self.bg_color {
if channels == bg_color.channels() {
bg_index = i;
}
}
table.push_all(channels)
}
for _ in 0..((2 << n) - num_colors) {
table.push_all(&[0, 0, 0]);
}
(Some(table), bg_index as u8)
} else if let Some(bg_color) = self.bg_color {
flags |= 1 << 7;
let mut table = Vec::with_capacity(6);
table.push_all(&bg_color.channels()[..3]);
table.push_all(&[0, 0, 0]);
(Some(table), 0)
} else {
(None, 0)
};
try!(w.write_u8(flags));
try!(w.write_u8(bg_index));
try!(w.write_u8(0));
if let Some(global_table) = global_table {
try!(w.write_all(&global_table));
}
Ok(())
}
fn write_control_ext<W: Writer>(&mut self,
w: &mut W,
delay: u16,
transparent: Option<usize>
) -> IoResult<()>
{
try!(w.write_u8(Block::Extension as u8));
try!(w.write_u8(Extension::Control as u8));
try!(w.write_u8(4));
let mut field = 0;
field |= (DisposalMethod::None as u8) << 2;
let idx = if let Some(idx) = transparent {
field |= 1;
idx as u8
} else {
0
};
try!(w.write_u8(field));
try!(w.write_le_u16(delay));
try!(w.write_u8(idx));
w.write_u8(0)
}
fn write_descriptor<W: Writer>(&mut self,
w: &mut W,
table_len: Option<usize>
) -> IoResult<()>
{
try!(w.write_u8(Block::Image as u8));
try!(w.write_le_u16(0));
try!(w.write_le_u16(0));
let height = self.image.height();
let width = self.image.width();
try!(w.write_le_u16(width as u16));
try!(w.write_le_u16(height as u16));
if let Some(len) = table_len {
w.write_u8(flag_n(len) | 0x80)
} else {
w.write_u8(0)
}
}
fn write_indices<W: Writer>(&mut self,
w: &mut W,
indices: &[u8],
) -> IoResult<()>
{
let code_size = match flag_n(indices.len()) + 1 {
1 => 2,
n => n
};
let mut encoded_data = Vec::new();
try!(lzw::encode(indices, LsbWriter::new(&mut encoded_data), code_size));
try!(w.write_u8(code_size));
for chunk in encoded_data.chunks(255) {
try!(w.write_u8((chunk.len()) as u8));
try!(w.write_all(chunk));
}
w.write_u8(0)
}
fn write_image_simple<W: Writer>(&mut self,
w: &mut W,
hist: &[(Rgba<u8>, usize)],
transparent: Option<usize>,
) -> IoResult<()>
{
let t_idx = match transparent { Some(i) => i as u8, None => 0 };
let data: Vec<u8> = self.image.pixels().map(|p| {
if let Some(idx) = hist.iter().position(|x| x.0 == *p) {
idx as u8
} else {
t_idx
}
}).collect();
self.write_indices(w, &data)
}
fn write_true_color<W: Writer>(&mut self,
w: &mut W,
hist: Vec<(Rgba<u8>, usize)>,
transparent: Option<usize>
) -> IoResult<()>
{
let mut hist = hist;
if let Some(transparent) = transparent {
let _ = hist.swap_remove(transparent);
}
let transparent = Some(0);
let indices: Vec<u32> = self.image.pixels().map(|p| {
if let Some(idx) = hist.iter().position(|x| x.0 == *p) {
idx as u32
} else {
0
}
}).collect();
let mut chunk_indices = Vec::with_capacity(
self.image.width() as usize * self.image.height() as usize
);
for (j, chunk) in hist.chunks(255).enumerate() {
chunk_indices.clear();
for &idx in indices.iter() {
let i: i64 = idx as i64 - j as i64*255;
chunk_indices.push(if i < 0 || i > 255 { 0 } else { i as u8 + 1 })
}
let num_local_colors = chunk.len() + 1;
let n = flag_n(num_local_colors);
try!(self.write_control_ext(w, 0, transparent));
try!(self.write_descriptor(w, Some(num_local_colors)));
try!(w.write_all(&TRANSPARENT.channels()[..3]));
for &(color, _) in chunk.iter() {
try!(w.write_all(&color.channels()[..3]));
}
for _ in 0..((2 << n) - num_local_colors) {
try!(w.write_all(&[0, 0, 0]));
}
try!(self.write_indices(w, &chunk_indices));
}
Ok(())
}
fn write_indexed_colors<W: Writer>(&mut self, w: &mut W, n: u8) -> IoResult<()> {
if n < 64 {
return Err(old_io::IoError{
kind: old_io::InvalidInput,
desc: "Unsupported number of colors.",
detail: Some(
format!("{} colors < 64 colors", n))
})
}
let nq = nq::NeuQuant::new(3, 256, self.image.as_slice());
for pixel in self.image.pixels_mut() {
nq.map_color(pixel);
}
let (hist, transparent) = self.histogram();
let num_local_colors = hist.len();
let n = flag_n(num_local_colors);
try!(self.write_control_ext(w, 0, transparent));
try!(self.write_descriptor(w, Some(num_local_colors)));
for &(color, _) in hist.iter() {
try!(w.write_all(&color.channels()[..3]));
}
for _ in 0..((2 << n) - num_local_colors) {
try!(w.write_all(&[0, 0, 0]));
}
self.write_image_simple(w, &hist, transparent)
}
#[allow(dead_code)]
fn write_nab<W: Writer>(&mut self, w: &mut W, n: u16) -> IoResult<()> {
try!(w.write_u8(Block::Extension as u8));
try!(w.write_u8(Extension::Application as u8));
try!(w.write_u8(0x0B));
try!(w.write_all(b"NETSCAPE2.0"));
try!(w.write_u8(0x03));
try!(w.write_u8(0x01));
try!(w.write_le_u16(n));
w.write_u8(0)
}
}
fn flag_n(size: usize) -> u8 {
match size {
0 ...2 => 0,
3 ...4 => 1,
5 ...8 => 2,
7 ...16 => 3,
17 ...32 => 4,
33 ...64 => 5,
65 ...128 => 6,
129...256 => 7,
_ => 7
}
}