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
mod ispc;
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub enum Format {
RGB8,
RGBA8,
}
impl Format {
fn num_channels(&self) -> u8 {
match self {
Self::RGB8 => 3,
Self::RGBA8 => 4,
}
}
}
pub struct Image<'a> {
pixels: &'a [u8],
width: u32,
height: u32,
format: Format,
}
impl<'a> Image<'a> {
pub fn new(pixels: &'a [u8], width: u32, height: u32, format: Format) -> Self {
Self {
pixels,
width,
height,
format,
}
}
}
pub fn downsample(src: &Image, target_width: u32, target_height: u32) -> Vec<u8> {
assert!(src.width >= target_width, "The width of the source image is less than the target's width. You are trying to upsample rather than downsample");
assert!(src.height >= target_height, "The width of the source image is less than the target's width. You are trying to upsample rather than downsample");
let mut output = Vec::new();
output.resize(
(target_width * target_height * src.format.num_channels() as u32) as usize,
0,
);
unsafe {
ispc::downsample_ispc::resample(
src.width,
src.height,
src.width,
src.format.num_channels(),
target_width,
target_height,
src.pixels.as_ptr(),
output.as_mut_ptr(),
)
}
output
}