summaryrefslogtreecommitdiff
path: root/dichroism/src/models/photo.rs
blob: 8c1435e62f3244b8ea2c3f0b4b4bf3aea397847a (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
use crate::config::CONFIG_INSTANCE;
use crate::error::DichroismError;
use crate::result::Result;
use image::DynamicImage;
use std::path::PathBuf;
use uuid::Uuid;

#[derive(Debug, Queryable, Serialize, Clone)]
pub struct Photo {
    pub filename: String,
}

impl Photo {
    pub fn from_filename(filename: String) -> Self {
        Self { filename }
    }

    pub fn from_image(image: &DynamicImage) -> Result<Self> {
        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 filename = path
            .file_name()
            .ok_or(DichroismError::ImageWrite)?
            .to_str()
            .ok_or(DichroismError::ImageWrite)?;
        Ok(Self::from_filename(String::from(filename)))
    }
}