crates/korp-map-quality/src/image_io.rs
//! PNG in and out (RGB; alpha dropped).
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::path::Path;
use crate::metrics::Rgb;
/// Read a PNG as RGB.
pub fn read_png(path: &Path) -> Result<Rgb, String> {
let f = File::open(path).map_err(|e| format!("{path:?}: {e}"))?;
let mut d = png::Decoder::new(BufReader::new(f));
d.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut r = d.read_info().map_err(|e| format!("{path:?}: {e}"))?;
let mut buf = vec![0; r.output_buffer_size().ok_or("png too large")?];
let info = r
.next_frame(&mut buf)
.map_err(|e| format!("{path:?}: {e}"))?;
let ch = match info.color_type {
png::ColorType::Rgba => 4,
png::ColorType::Rgb => 3,
png::ColorType::GrayscaleAlpha => 2,
png::ColorType::Grayscale => 1,
png::ColorType::Indexed => return Err(format!("{path:?}: indexed png after expand")),
};
let px = buf[..info.buffer_size()]
.chunks_exact(ch)
.map(|c| {
if ch >= 3 {
[c[0], c[1], c[2]]
} else {
[c[0], c[0], c[0]]
}
})
.collect();
Ok(Rgb {
width: info.width,
height: info.height,
px,
})
}
/// Write RGB as PNG.
pub fn write_png(path: &Path, img: &Rgb) -> Result<(), String> {
let f = File::create(path).map_err(|e| format!("{path:?}: {e}"))?;
let mut e = png::Encoder::new(BufWriter::new(f), img.width, img.height);
e.set_color(png::ColorType::Rgb);
e.set_depth(png::BitDepth::Eight);
let mut w = e.write_header().map_err(|e| e.to_string())?;
let raw: Vec<u8> = img.px.iter().flatten().copied().collect();
w.write_image_data(&raw).map_err(|e| e.to_string())
}
/// A land/coverage mask as a PNG for eyes: land not covered in red, covered in green,
/// off land dark.
pub fn write_mask(
path: &Path,
w: u32,
h: u32,
land: &[bool],
covered: impl Fn(usize) -> bool,
) -> Result<(), String> {
let px = (0..land.len())
.map(|i| match (land[i], covered(i)) {
(true, true) => [40, 150, 70],
(true, false) => [220, 40, 40],
(false, true) => [30, 60, 110],
(false, false) => [12, 14, 20],
})
.collect();
write_png(
path,
&Rgb {
width: w,
height: h,
px,
},
)
}