summaryrefslogtreecommitdiff
path: root/dichroism/src/image_api.rs
blob: 97faeadf0b710b6408e1eab42eac93e83fe8955c (plain) (blame)
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
use crate::error::DichroismError;
use crate::result::Result;
use base64::decode;
use regex::Regex;

use once_cell::sync::Lazy;

static DATA_URI_RE: Lazy<Regex> = Lazy::new(|| {
    Regex::new("^data:image/(png|jpeg);base64,(?P<data>.+)").expect("Couldn't parse Regex.")
});

pub fn generate_images(data: &str) -> Result<()> {
    let bytes = decode(data)?;
    let img = image::load_from_memory(&bytes)?;
    //img.save("test_full.jpg")?;
    let _thumb = img.thumbnail(200, 200);
    //thumb.save("test_thumbnail.jpg")?;
    Ok(())
}

pub fn extract_data(uri: &str) -> Result<&str> {
    let caps = DATA_URI_RE
        .captures(uri)
        .ok_or(DichroismError::UriDataExtract)?;

    Ok(caps
        .name("data")
        .expect("Should never fail if regex succeeded.")
        .as_str())
}

#[cfg(test)]
mod tests {
    use super::*;

    const TEST_DATA_URI: &str = include_str!("unit_test_data/img_data_uri.txt");
    const TEST_DATA_BASE64: &str = include_str!("unit_test_data/test_data_base64.txt");

    #[test]
    fn test_generate_images() {
        generate_images(TEST_DATA_BASE64.trim()).unwrap();
    }

    #[test]
    fn test_extract_data() {
        let base64_data = extract_data(TEST_DATA_URI).unwrap();
        assert_eq!(TEST_DATA_BASE64.trim(), base64_data);
    }
}