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
69
70
71
72
73
74
75
76
77
78
79
80
use lenna_core::io::write::write_to_data;
use lenna_core::LennaImage;
use std::fs;
use std::io::{Seek, Write};
use std::path::{Path, PathBuf};
use zip::write::FileOptions;

pub mod plugins;
mod wasm;

pub fn zip_images<T>(
    images: Vec<&mut Box<lenna_core::LennaImage>>,
    format: image::ImageOutputFormat,
    writer: T,
    method: zip::CompressionMethod,
) -> zip::result::ZipResult<()>
where
    T: Write + Seek,
{
    let mut zip = zip::ZipWriter::new(writer);
    let options = FileOptions::default()
        .compression_method(method)
        .unix_permissions(0o755);

    for entry in images {
        let path = Path::new(&entry.name);
        let name = path.strip_prefix(Path::new(&entry.path)).unwrap();
        #[allow(deprecated)]
        zip.start_file_from_path(name, options)?;
        let buffer = write_to_data(entry, format.clone()).unwrap();

        zip.write_all(&*buffer)?;
    }
    zip.finish()?;
    Result::Ok(())
}

pub fn images_in_path(path: &PathBuf) -> Vec<PathBuf> {
    let mut images: Vec<PathBuf> = Vec::new();
    let path = Path::new(path);
    match path.is_dir() {
        true => {
            for entry in fs::read_dir(path).unwrap() {
                let entry = entry.unwrap();
                let path = entry.path();
                if path.is_dir() {
                } else {
                    images.push(path);
                }
            }
        }
        false => images.push(path.into()),
    }
    images
}

pub fn write_to_path(mut img: Box<LennaImage>, path: String, ext: String) {
    let ext = ext.as_str();
    img.path = path.clone();
    match ext {
        "zip" => {
            img.name = format!("{}.jpg", img.name);
            let images = vec![&mut img];
            let file = std::fs::File::create(&path).unwrap();
            zip_images(
                images,
                image::ImageOutputFormat::Jpeg(80),
                file,
                zip::CompressionMethod::DEFLATE,
            )
            .unwrap();
        }
        "png" | "PNG" => {
            lenna_core::io::write::write_to_file(&img, image::ImageOutputFormat::Png).unwrap();
        }
        _ => {
            lenna_core::io::write::write_to_file(&img, image::ImageOutputFormat::Jpeg(80)).unwrap();
        }
    }
}