1use std::io::Write;
2pub mod pixel;
4pub mod header;
6use header::Header;
7use pixel::Pixel;
8pub mod utils;
10use utils::*;
11mod rotate;
12use rotate::rotate;
13
14pub struct Img {
16 header: Header,
17 pub pixels: Vec<Vec<Pixel>>
19}
20
21impl Img {
22
23
24 pub fn new(pixels: Vec<Vec<Pixel>>) -> Img {
26 let height = pixels.len() as u32;
27 let width = pixels[0].len() as u32;
28 let header = Header::new(width, height, width * height);
29 Img {
30 header: header, pixels: pixels
31 }
32 }
33
34
35 pub fn get_binary_data(&self) -> Vec<u8>{
37 let mut data = self.header.get_binary_data();
38 for i in (0..self.pixels.len()).rev(){
39 for pixel in self.pixels[i].iter() {
40 data.push(pixel.b);
41 data.push(pixel.g);
42 data.push(pixel.r);
43 }
44 for _i in 0..(4 - (self.pixels[0].len() as u32 * 3) % 4){
45 if (self.pixels[0].len() as u32 * 3) % 4 == 0 {
46 break;
47 }
48 data.push(0);
49 }
50 }
51 let mut size = transform_u32_to_array_of_u8(data.len() as u32);
52 for i in 0..4 {
53 data[i+2] = size[i];
54 }
55 size = transform_u32_to_array_of_u8(self.pixels.len() as u32 * ((self.pixels[0].len() as u32 * 3 + 7) & !7) as u32 / 16);
56 for i in 0..4 {
57 data[i+34] = size[i];
58 }
59 data
60 }
61
62
63 pub fn write_image(&self, path: &str){
72 if !path.contains(".bmp") {
73 panic!("I am not a bmp image!");
74 }
75 let width = self.pixels[0].len();
76 for row in self.pixels.iter(){
77 if row.len() != width {
78 panic!("The pixel array does not have equal row sizes!")
79 }
80 }
81 let mut data = std::fs::File::create(path).unwrap();
82 let img = Img::new(self.pixels.clone());
83 let bdata = img.get_binary_data();
84 data.write(&bdata).unwrap();
85 }
86
87
88 pub fn rotate(&mut self){
90 self.pixels = rotate(&mut self.pixels);
91 }
92}