clay_utils/
output.rs

1use std::{fs, cmp::max, ffi::OsStr};
2use clay_core::{self, buffer::Image};
3
4
5fn from_os(os_str: &OsStr) -> String {
6    os_str.to_string_lossy().into_owned()
7}
8
9pub fn save_screenshot(image: &Image, lossless: bool) -> clay_core::Result<String> {
10    fs::create_dir_all("screenshots")?;
11    let maxn = fs::read_dir("screenshots")?
12    .filter_map(|f_| f_.ok().map(|f| f.path()).and_then(|p| {
13        p.file_stem().map(|s| from_os(s))
14        .and_then(|n| n.parse::<i32>().ok())
15    }))
16    .fold(0, |b, n| max(b, n)) + 1;
17
18    let ext = if lossless { "png" } else { "jpg" };
19
20    let filename = format!("screenshots/{:04}.{}", maxn, ext);
21    image.save_to_file(&filename)?;
22    Ok(filename)
23}