Skip to main content

lib_jsl_file_io/
jpeg_files.rs

1//! Reading and writing JPEG files with the workspace's baseline codec.
2//!
3//! See the book entry [Image files](https://jwkunz.github.io/lib_jsl/book/foundations/images.html#baseline-jpeg).
4
5use lib_jsl_core::ErrorsJSL;
6use crate::jpeg::{JpegImage, jpeg_decode, jpeg_encode};
7use std::path::Path;
8
9/// Reads and decodes a baseline JPEG file (grayscale or RGB).
10pub fn read_jpeg_file(path: impl AsRef<Path>) -> Result<JpegImage, ErrorsJSL> {
11    let data = std::fs::read(path).map_err(|_| ErrorsJSL::RuntimeError("Could not read the JPEG file."))?;
12    jpeg_decode(&data)
13}
14
15/// Encodes `image` at `quality` (1 to 100) and writes it to `path`.
16pub fn write_jpeg_file(path: impl AsRef<Path>, image: &JpegImage, quality: u8) -> Result<(), ErrorsJSL> {
17    let bytes = jpeg_encode(&image.pixels, image.width, image.height, image.channels, quality)?;
18    std::fs::write(path, bytes).map_err(|_| ErrorsJSL::RuntimeError("Could not write the JPEG file."))
19}
20
21#[cfg(test)]
22mod tests {
23    use super::*;
24
25    #[test]
26    fn file_round_trip_is_close() {
27        let (w, h) = (40, 24);
28        let pixels: Vec<u8> = (0..w * h * 3).map(|i| ((i / 3 % w) * 6 + (i % 3) * 20) as u8).collect();
29        let img = JpegImage { width: w, height: h, channels: 3, pixels };
30        let path = std::env::temp_dir().join(format!("lib_jsl_jpeg_test_{}.jpg", std::process::id()));
31        write_jpeg_file(&path, &img, 95).unwrap();
32        let back = read_jpeg_file(&path).unwrap();
33        std::fs::remove_file(&path).ok();
34        assert_eq!((back.width, back.height, back.channels), (w, h, 3));
35        let mean_err = img.pixels.iter().zip(&back.pixels).map(|(&a, &b)| (a as f64 - b as f64).abs()).sum::<f64>() / img.pixels.len() as f64;
36        assert!(mean_err < 4.0, "mean error {mean_err}");
37        assert!(read_jpeg_file(&path).is_err());
38    }
39}