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
use std::io::{self, Read};
use byteorder::ReadBytesExt;
pub struct RGB256 {
pub r: u8,
pub g: u8,
pub b: u8,
}
pub struct RGB64 {
pub r: u8,
pub g: u8,
pub b: u8,
}
pub struct RGBA256 {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
pub struct Grayscale256 {
pub v: u8,
pub a: u8,
}
pub enum Pixels {
RGBA(Vec<RGBA256>),
Grayscale(Vec<Grayscale256>),
Indexed(Vec<u8>),
}
impl Pixels {
pub fn rgba_from_read<R>(read: &mut R, pixels_size: usize) -> io::Result<Self>
where
R: Read,
{
const BYTES_PER_PIXEL: usize = 4;
if pixels_size % BYTES_PER_PIXEL != 0 {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Pixels size is not multiple of 4 (RGBA): {}", pixels_size),
));
}
let pixel_count = pixels_size / BYTES_PER_PIXEL;
let mut pixels = Vec::with_capacity(pixel_count);
for _ in 0..pixel_count {
pixels.push(RGBA256 {
r: read.read_u8()?,
g: read.read_u8()?,
b: read.read_u8()?,
a: read.read_u8()?,
});
}
Ok(Pixels::RGBA(pixels))
}
pub fn grayscale_from_read<R>(read: &mut R, pixels_size: usize) -> io::Result<Self>
where
R: Read,
{
const BYTES_PER_PIXEL: usize = 2;
if pixels_size % BYTES_PER_PIXEL != 0 {
return Err(io::Error::new(
io::ErrorKind::Other,
format!(
"Pixels size is not multiple of 2 (Grayscale): {}",
pixels_size
),
));
}
let pixel_count = pixels_size / BYTES_PER_PIXEL;
let mut pixels = Vec::with_capacity(pixel_count);
for _ in 0..pixel_count {
pixels.push(Grayscale256 {
v: read.read_u8()?,
a: read.read_u8()?,
});
}
Ok(Pixels::Grayscale(pixels))
}
pub fn indexed_from_read<R>(read: &mut R, pixels_size: usize) -> io::Result<Self>
where
R: Read,
{
let index_count = pixels_size;
let mut indices = Vec::with_capacity(index_count);
for _ in 0..index_count {
indices.push(read.read_u8()?);
}
Ok(Pixels::Indexed(indices))
}
}