summaryrefslogtreecommitdiff
path: root/src/bitmap.rs
blob: afd6bf51fd8e766502769e713acc6fd7d5d0a159 (plain)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// SPDX-License-Identifier: LGPL-3.0-or-later
/*
 * libopenraw - bitmap.rs
 *
 * Copyright (C) 2022-2023 Hubert Figuière
 *
 * This library is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

//! Trait and types for various bitmap data, iamges, etc. and other
//! geometry.

use crate::DataType;

/// An image buffer carries the data and the dimension. It is used to
/// carry pipeline input and ouput as dimensions can change.
pub struct ImageBuffer<T> {
    pub(crate) data: Vec<T>,
    pub(crate) width: u32,
    pub(crate) height: u32,
    /// bits per channel
    pub(crate) bpc: u16,
    /// number of channel
    pub(crate) cc: u32,
}

impl<T> ImageBuffer<T> {
    /// Create an image buffer.
    pub(crate) fn with_data(data: Vec<T>, width: u32, height: u32, bpc: u16, cc: u32) -> Self {
        Self {
            data,
            width,
            height,
            bpc,
            cc,
        }
    }

    /// Return the pixel RGB value at `x` and `y`.
    pub fn pixel_at(&self, x: u32, y: u32) -> Option<Vec<T>>
    where
        T: Copy,
    {
        if x > self.width || y > self.height {
            return None;
        }
        let pos = ((y * self.width * self.cc) + x * self.cc) as usize;
        let pixel = &self.data[pos..pos + self.cc as usize];

        Some(pixel.to_vec())
    }
}

impl ImageBuffer<f64> {
    pub fn into_u16(self) -> ImageBuffer<u16> {
        ImageBuffer::<u16>::with_data(
            self.data
                .iter()
                .map(|v| (*v * u16::MAX as f64).round() as u16)
                .collect(),
            self.width,
            self.height,
            16,
            self.cc,
        )
    }
}

impl ImageBuffer<u16> {
    pub fn into_f64(self) -> ImageBuffer<f64> {
        ImageBuffer::<f64>::with_data(
            self.data
                .iter()
                .map(|v| *v as f64 / u16::MAX as f64)
                .collect(),
            self.width,
            self.height,
            16,
            self.cc,
        )
    }
}

/// Trait for bitmap objects.
pub trait Bitmap {
    fn data_type(&self) -> DataType;
    /// The data size is bytes
    fn data_size(&self) -> usize;
    /// Pixel width
    fn width(&self) -> u32;
    /// Pixel height
    fn height(&self) -> u32;
    /// Bits per component
    fn bpc(&self) -> u16;
    /// Image data in 8 bits
    fn data8(&self) -> Option<&[u8]>;
}

pub trait Image: Bitmap {
    /// Image data in 16 bits
    fn data16(&self) -> Option<&[u16]>;
}

/// Rectangle struct.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Rect {
    pub x: u32,
    pub y: u32,
    pub width: u32,
    pub height: u32,
}

impl Rect {
    pub fn new(origin: Point, size: Size) -> Rect {
        Rect {
            x: origin.x,
            y: origin.y,
            width: size.width,
            height: size.height,
        }
    }

    /// Generate a `Vec<u32>` with the values in x, y, w, h order.
    pub fn to_vec(&self) -> Vec<u32> {
        [self.x, self.y, self.width, self.height].to_vec()
    }
}

/// Point struct
#[derive(Debug, PartialEq)]
pub struct Point {
    pub x: u32,
    pub y: u32,
}

/// Size struct
#[derive(Debug, PartialEq)]
pub struct Size {
    pub width: u32,
    pub height: u32,
}

/// Encapsulate data 8 or 16 bits
pub(crate) enum Data {
    Data8(Vec<u8>),
    Data16(Vec<u16>),
    Tiled((Vec<Vec<u8>>, (u32, u32))),
}

impl Default for Data {
    fn default() -> Data {
        Data::Data16(Vec::default())
    }
}

impl std::fmt::Debug for Data {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        f.write_str(&match *self {
            Self::Data8(ref v) => format!("Data(Data8([{}]))", v.len()),
            Self::Data16(ref v) => format!("Data(Data16([{}]))", v.len()),
            Self::Tiled((ref v, sz)) => format!("Data(Tiled([{}], {:?}))", v.len(), sz),
        })
    }
}