eye_hal/format.rs
1use std::cmp::{Eq, PartialEq};
2use std::fmt;
3use std::hash::Hash;
4
5#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6/// Pixel format type used to describe image pixels.
7///
8/// Arbitrary formats can be wrapped in the Custom variant.
9/// The other variants have values describing the depth of a whole pixel in bits.
10pub enum PixelFormat {
11 /// Special type for application defined formats
12 Custom(String),
13
14 /// Z buffers
15 Depth(u32),
16 /// Grayscale
17 Gray(u32),
18
19 /// Blue, Green, Red
20 Bgr(u32),
21 /// Red, Green, Blue
22 Rgb(u32),
23
24 /// JPEG compression
25 Jpeg,
26}
27
28impl PixelFormat {
29 /// Returns the number of bits of a whole pixel
30 pub fn bits(&self) -> Option<u32> {
31 match self {
32 // Custom
33 PixelFormat::Custom(_) => None,
34 // Uncompressed
35 PixelFormat::Depth(bits) => Some(*bits),
36 PixelFormat::Gray(bits) => Some(*bits),
37 PixelFormat::Bgr(bits) => Some(*bits),
38 PixelFormat::Rgb(bits) => Some(*bits),
39 // Compressed
40 PixelFormat::Jpeg => None,
41 }
42 }
43}
44
45impl fmt::Display for PixelFormat {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 write!(f, "{:?}", self)
48 }
49}
50
51#[derive(Clone, Debug)]
52/// Image buffer format description
53pub struct ImageFormat {
54 /// Width in pixels
55 pub width: u32,
56 /// Height in pixels
57 pub height: u32,
58 /// PixelFormat
59 pub pixfmt: PixelFormat,
60 /// Length of a pixel row in bytes
61 pub stride: Option<usize>,
62}
63
64impl ImageFormat {
65 /// Returns an image format representation
66 ///
67 /// # Arguments
68 ///
69 /// * `width` - Width in pixels
70 /// * `height` - Height in pixels
71 /// * `pixfmt` - PixelFormat
72 ///
73 /// # Example
74 ///
75 /// ```
76 /// use eye_hal::format::{ImageFormat, PixelFormat};
77 /// let format = ImageFormat::new(1280, 720, PixelFormat::Rgb(24));
78 /// ```
79 pub fn new(width: u32, height: u32, pixfmt: PixelFormat) -> Self {
80 let stride = pixfmt.bits().map(|bits| (width * (bits / 8)) as usize);
81
82 ImageFormat {
83 width,
84 height,
85 pixfmt,
86 stride,
87 }
88 }
89
90 /// Builder pattern constructor
91 ///
92 /// # Arguments
93 ///
94 /// * `stride` - Length of a pixel row in bytes
95 pub fn stride(mut self, stride: usize) -> Self {
96 self.stride = Some(stride);
97 self
98 }
99}