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
use crate::bit::BitStreamWriter;
use crate::{Bmp, BmpError, BmpHeader, B, HEADER_SIZE, M};
use std::io::Write;
impl Bmp {
pub fn write<T: Write>(&self, mut to: T) -> Result<(), BmpError> {
let width = self.width as u32;
let height = self.height() as u32;
let header = BmpHeader { height, width };
let padding = header.padding() as u8;
header.write(&mut to)?;
let mut writer = BitStreamWriter::new(&mut to);
for i in 0..height as usize {
for j in 0..width as usize {
if self.get(i, j) {
writer.write(1, 1)?;
} else {
writer.write(0, 1)?;
}
}
writer.write(0, 8 - (width % 8) as u8)?;
writer.write(0, padding * 8)?;
}
writer.flush()?;
Ok(())
}
}
impl BmpHeader {
pub fn write<T: Write>(&self, to: &mut T) -> Result<(), BmpError> {
let bytes_per_row = self.bytes_per_row();
let padding = self.padding();
let data_size = (bytes_per_row + padding) * (self.height as u32);
let total_size = HEADER_SIZE + data_size;
to.write_all(&[B, M])?;
to.write_all(&total_size.to_le_bytes())?;
to.write_all(&0u16.to_le_bytes())?;
to.write_all(&0u16.to_le_bytes())?;
to.write_all(&HEADER_SIZE.to_le_bytes())?;
to.write_all(&40u32.to_le_bytes())?;
to.write_all(&(self.width as u32).to_le_bytes())?;
to.write_all(&(self.height as u32).to_le_bytes())?;
to.write_all(&1u16.to_le_bytes())?;
to.write_all(&1u16.to_le_bytes())?;
to.write_all(&0u32.to_le_bytes())?;
to.write_all(&data_size.to_le_bytes())?;
to.write_all(&512u32.to_le_bytes())?;
to.write_all(&512u32.to_le_bytes())?;
to.write_all(&2u32.to_le_bytes())?;
to.write_all(&2u32.to_le_bytes())?;
to.write_all(&0x00_FF_FF_FFu32.to_le_bytes())?;
to.write_all(&0x00_00_00_00u32.to_le_bytes())?;
Ok(())
}
}