summaryrefslogblamecommitdiff
path: root/dichroism/src/image_api.rs
blob: 3eff88e170a9b92650e10c832adf524ef4482fe3 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
                                 



                          




                                                                                            
 
                                                  

                                               


                                         
          



                                                                                              

 






                                                
                                                        


                  




                                                                                





                                                                                       

           


                                                               

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

    // TODO: gather and return related images as a tuple. then in another function, write them
    // out to the filesystem and return NewImages using the resulting paths. The pathnames
    // *probably* need to be UUIDs.
}

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