summaryrefslogtreecommitdiff
path: root/dichroism/src/image_api.rs
blob: d1649d5f1c7501c1e3ad637126c8edcd0ae87a43 (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
use crate::result::Result;
use base64::decode;
use regex::Regex;

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

pub fn data_uri_to_files(uri: &str) -> Result<()> {
    let caps = if let Some(c) = DATA_URI_RE.captures(uri) {
        c
    } else {
        todo!();
    };

    let data = caps
        .name("data")
        .expect("Data URI data extraction should never fail.")
        .as_str();

    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(())
}

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

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

    #[test]
    fn test_data_uri_to_files() {
        data_uri_to_files(TEST_DATA_URI).unwrap();
    }
}