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
|
use crate::{
block::{
extension::{DisposalMethod, GraphicControl},
ColorTable, ImageDescriptor, IndexedImage, Version,
},
EncodingError,
};
pub struct ImageBuilder {
left_offset: u16,
top_offset: u16,
width: u16,
height: u16,
color_table: Option<ColorTable>,
delay: u16,
disposal_method: DisposalMethod,
transparent_index: Option<u8>,
indicies: Vec<u8>,
}
impl ImageBuilder {
pub fn new(width: u16, height: u16) -> Self {
Self {
left_offset: 0,
top_offset: 0,
width,
height,
color_table: None,
delay: 0,
disposal_method: DisposalMethod::NoAction,
transparent_index: None,
indicies: vec![],
}
}
pub fn offset(mut self, left: u16, top: u16) -> Self {
self.left_offset = left;
self.top_offset = top;
self
}
pub fn palette(mut self, table: ColorTable) -> Self {
self.color_table = Some(table);
self
}
/// Time to wait, in hundreths of a second, before this image is drawn
pub fn delay(mut self, hundreths: u16) -> Self {
self.delay = hundreths;
self
}
pub fn disposal_method(mut self, method: DisposalMethod) -> Self {
self.disposal_method = method;
self
}
pub fn transparent_index(mut self, index: Option<u8>) -> Self {
self.transparent_index = index;
self
}
pub fn required_version(&self) -> Version {
if self.delay > 0
|| self.disposal_method != DisposalMethod::NoAction
|| self.transparent_index.is_some()
{
Version::Gif89a
} else {
Version::Gif87a
}
}
pub fn get_graphic_control(&self) -> Option<GraphicControl> {
if self.required_version() == Version::Gif89a {
if let Some(transindex) = self.transparent_index {
Some(GraphicControl::new(
self.disposal_method,
false,
true,
self.delay,
transindex,
))
} else {
Some(GraphicControl::new(
self.disposal_method,
false,
false,
self.delay,
0,
))
}
} else {
None
}
}
pub fn indicies(mut self, indicies: Vec<u8>) -> Self {
self.indicies = indicies;
self
}
pub fn build(self) -> Result<IndexedImage, EncodingError> {
let expected_len = self.width as usize * self.height as usize;
if self.indicies.len() != expected_len {
return Err(EncodingError::IndicieSizeMismatch {
expected: expected_len,
got: self.indicies.len(),
});
}
let mut imgdesc = ImageDescriptor {
left: self.left_offset,
top: self.top_offset,
width: self.width,
height: self.height,
packed: 0, // Set later
};
if let Some(lct) = &self.color_table {
imgdesc.set_color_table_present(true);
imgdesc.set_color_table_size(lct.packed_len());
}
Ok(IndexedImage {
image_descriptor: imgdesc,
local_color_table: self.color_table,
indicies: self.indicies,
})
}
}
|