summaryrefslogtreecommitdiff
path: root/dichroism/src/image_service.rs
blob: 3a31e045df32dd9a5058b2731abdd2bc2dca8e04 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use crate::config::CONFIG_INSTANCE;
use crate::constants::{PHOTO_BASE_XY, PHOTO_FULLSIZE_XY, PHOTO_THUMBNAIL_XY};
use crate::error::DichroismError;
use crate::models::{Photo, PhotoSet};
use base64::decode;
use image::imageops::FilterType;
use image::DynamicImage;
use image::GenericImageView;
use once_cell::sync::Lazy;
use regex::Regex;
use std::path::PathBuf;
use uuid::Uuid;

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

pub fn generate_photo_set(uri: &str) -> Result<PhotoSet, DichroismError> {
    let data = DATA_URI_RE
        .captures(uri)
        .ok_or_else(|| DichroismError::UriDataExtract("Failed to parse URI".to_string()))?
        .name("data")
        .ok_or_else(|| DichroismError::UriDataExtract("Failed to extract data".to_string()))?
        .as_str();
    let original = image::load_from_memory(&decode(data)?)?;
    let fullsize = original.resize(PHOTO_FULLSIZE_XY, PHOTO_FULLSIZE_XY, FilterType::Lanczos3);
    let base = original.resize(PHOTO_BASE_XY, PHOTO_BASE_XY, FilterType::Lanczos3);

    let (width, height) = original.dimensions();
    let thumbnail = if width > height {
        let offset = (width - height) / 2;
        original.crop_imm(offset, 0, width - offset * 2, height)
    } else {
        let offset = (height - width) / 2;
        original.crop_imm(0, offset, width, height - offset * 2)
    }
    .resize(PHOTO_THUMBNAIL_XY, PHOTO_THUMBNAIL_XY, FilterType::Lanczos3);

    Ok(PhotoSet {
        id: None,
        original: generate_photo(&original)?,
        fullsize: generate_photo(&fullsize)?,
        base: generate_photo(&base)?,
        thumbnail: generate_photo(&thumbnail)?,
    })
}

fn generate_photo(image: &DynamicImage) -> Result<Photo, DichroismError> {
    let base_name = Uuid::new_v3(&Uuid::NAMESPACE_OID, &image.to_bytes())
        .to_hyphenated()
        .to_string();
    let mut path = PathBuf::from(&CONFIG_INSTANCE.img_root);
    path.push(base_name);
    path.set_extension("jpg");
    image.save(&path)?;

    let id = path
        .file_name()
        .ok_or_else(|| {
            DichroismError::ImageWrite("Error extracting filename from path".to_string())
        })?
        .to_str()
        .ok_or_else(|| {
            DichroismError::ImageWrite("Error converting filename to slice".to_string())
        })?;
    Ok(Photo::new(String::from(id)))
}