use std::fs::File;
use std::io::{self, Read, Seek, SeekFrom, Write};
use crate::bmp::bmp_info_header::BmpInfoHeader;
pub struct BmpColourTable {
pub data: Vec<(u8, u8, u8, u8)>
}
impl BmpColourTable {
pub fn new() -> Self {
BmpColourTable {
data: Vec::new()
}
}
pub fn build_from_file(file: &mut File, info_header: &BmpInfoHeader) -> io::Result<Self> {
let color_table_size = u32::from_le_bytes(info_header.colours_used) * 4;
let mut color_table = BmpColourTable {
data: vec![(0, 0, 0, 0); color_table_size as usize],
};
file.seek(SeekFrom::Start(54))?;
let mut buffer = vec![0; (color_table_size) as usize];
file.read(&mut buffer)?;
color_table.data = buffer.chunks_exact(4)
.map(|chunk| (chunk[0], chunk[1], chunk[2], chunk[3]))
.collect::<Vec<_>>();
Ok(color_table)
}
pub fn write_to_file(&self, file: &mut File) -> io::Result<()> {
for (r, g, b, a) in &self.data {
file.write(&[*b, *g, *r, *a])?;
}
println!("Wrote BMP color table to file");
Ok(())
}
}
impl Clone for BmpColourTable {
fn clone(&self) -> Self {
BmpColourTable {
data: self.data.clone()
}
}
}