Skip to main content

fractal_gen/
image.rs

1use std::io::Write;
2/// Create an RGB Pixel,
3pub mod pixel;
4/// View the header data of the image!
5pub mod header;
6use header::Header;
7use pixel::Pixel;
8/// Use the utility functions.
9pub mod utils;
10use utils::*;
11mod rotate;
12use rotate::rotate;
13
14/// Structure of the Image.
15pub struct Img {
16    header: Header,
17    /// The pixels of the image as a 2D Vector.
18    pub pixels: Vec<Vec<Pixel>>    
19}
20
21impl Img {
22
23    
24    /// Create a BMP image.
25    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    /// Get the image's binary data.
36    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    /// Write the image into a file.
64    /// 
65    /// # Example
66    /// 
67    /// ```
68    /// let image = image::Img::new(pixels);
69    /// image.write_image("./myimage.bmp");
70    /// ```
71    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    /// Rotate the image by 90 degrees.
89    pub fn rotate(&mut self){
90        self.pixels = rotate(&mut self.pixels);
91    }
92}