use crate::error::DichroismError; use crate::result::Result; use base64::decode; use regex::Regex; use once_cell::sync::Lazy; static DATA_URI_RE: Lazy = Lazy::new(|| { Regex::new("^data:image/(png|jpeg);base64,(?P.+)").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); } }