audio_visualizer/util/
png.rs

1/*
2MIT License
3
4Copyright (c) 2021 Philipp Schuster
5
6Permission is hereby granted, free of charge, to any person obtaining a copy
7of this software and associated documentation files (the "Software"), to deal
8in the Software without restriction, including without limitation the rights
9to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10copies of the Software, and to permit persons to whom the Software is
11furnished to do so, subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all
14copies or substantial portions of the Software.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22SOFTWARE.
23*/
24use std::fs::File;
25use std::io::BufWriter;
26use std::path::Path;
27
28/// Writes RGB-bytes into the given file using [`png`]-crate.
29pub fn write_png_file_u8(file: &Path, rgb_data: &[u8], image_width: u32, image_height: u32) {
30    let file = File::create(file).unwrap();
31    let mut writer = BufWriter::new(file);
32
33    let mut encoder = png::Encoder::new(&mut writer, image_width, image_height);
34    encoder.set_color(png::ColorType::Rgb);
35    encoder.set_depth(png::BitDepth::Eight);
36    let mut writer = encoder.write_header().unwrap();
37
38    writer.write_image_data(rgb_data).unwrap();
39}
40
41/// Wrapper around [`write_png_file_u8`] that takes a vector of vectors with RGB-tuples.
42/// (rows, cols).
43pub fn write_png_file_rgb_tuples(file: &Path, rgb_image: &[Vec<(u8, u8, u8)>]) {
44    let width = rgb_image[0].len() as u32;
45    let height = rgb_image.len() as u32;
46
47    // data must be RGBA sequence: RGBARGBARGBA...
48    let rgb_data = rgb_image
49        .iter()
50        // get iter over each row
51        .flat_map(|row| row.iter())
52        .flat_map(|(r, g, b)| vec![r, g, b].into_iter())
53        .copied()
54        .collect::<Vec<u8>>();
55
56    write_png_file_u8(file, &rgb_data, width, height)
57}